在将Json.Net与ItemRequired = Required一起反序列化时忽略属性 [英] Ignore a property when deserializing using Json.Net with ItemRequired = Required.Always
问题描述
我正在使用Json.Net将类序列化和反序列化为json并返回.
I'm using Json.Net to serialize and deserialize classes to json and back.
我在标有[JsonObject(ItemRequired = Required.Always)]
(或Required.Always
)的类中添加了一个新的仅获取属性.结果为以下JsonSerializationException
I added to a class marked with [JsonObject(ItemRequired = Required.Always)]
(or Required.Always
) a new get-only property. That results in the following JsonSerializationException
:
Newtonsoft.Json.JsonSerializationException:在JSON中找不到必需的属性
'<PropertyName>'
我认为用JsonIgnore
标记该属性可以解决问题,但这不起作用.
I thought marking that property with JsonIgnore
would solve the issue, but that doesn't work.
如何告诉Json.Net应该忽略此属性?
How can I tell Json.Net that this property should be ignored?
这是重现此问题的一个最小示例:
Here's a minimal example reproducing the issue:
[JsonObject(ItemRequired = Required.Always)]
public class Hamster
{
public string FirstName { get; set; }
public string LastName { get; set; }
[JsonIgnore]
public string FullName { get { return FirstName + LastName; }}
}
private static void Main()
{
var hamster = new Hamster {FirstName = "Bar", LastName = "Arnon"};
var serializeObject = JsonConvert.SerializeObject(hamster);
var deserializeObject = JsonConvert.DeserializeObject<Hamster>(serializeObject);
}
推荐答案
显然,在这种情况下,JsonIgnore
仅控制序列化.需要JsonIgnore
来指定FullName
属性不应序列化为json表示形式.
Evidently JsonIgnore
will only control the serialization in this case. JsonIgnore
is required to specify that the FullName
property should not be serialized to the json representation.
要在反序列化期间忽略该属性,我们需要在JsonProperty
注释中添加Required = Required.Default
(这表示不需要).
To ignore the property during deserialization we need to add the JsonProperty
annotation with Required = Required.Default
(which means not required).
因此,这是避免JsonSerializationException
的方法:
So, this is how to avoid the JsonSerializationException
:
[JsonObject(ItemRequired = Required.Always)]
public class Hamster
{
public string FirstName { get; set; }
public string LastName { get; set; }
[JsonIgnore]
[JsonProperty(Required = Required.Default)]
public string FullName { get { return FirstName + LastName; }}
}
这篇关于在将Json.Net与ItemRequired = Required一起反序列化时忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!