Ignore a property when deserializing using Json.Net with ItemRequired = Required.Always

人走茶凉 提交于 2019-12-17 19:12:07

问题


I'm using Json.Net to serialize and deserialize classes to json and back.

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: Required property '<PropertyName>' not found in JSON

I thought marking that property with JsonIgnore would solve the issue, but that doesn't work.

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);
}

回答1:


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.

To ignore the property during deserialization we need to add the JsonProperty annotation with Required = Required.Default (which means not required).

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; }}
}


来源:https://stackoverflow.com/questions/30984416/ignore-a-property-when-deserializing-using-json-net-with-itemrequired-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!