使用带有 ItemRequired = Required.Always 的 Json.Net 反序列化时忽略属性

时间:2023-04-25
本文介绍了使用带有 ItemRequired = Required.Always 的 Json.Net 反序列化时忽略属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 Json.Net 将类序列化和反序列化为 json 并返回.

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

我向标有 [JsonObject(ItemRequired = Required.Always)](或 Required.Always)的类添加了一个新的 get-only 属性.这将导致以下 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>'

Newtonsoft.Json.JsonSerializationException: Required property '<PropertyName>' not found in JSON

我认为用 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; }}
}

这篇关于使用带有 ItemRequired = Required.Always 的 Json.Net 反序列化时忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Json.net 如何将对象序列化为值 下一篇:调用 JsonConvert.DeserializeObject&lt;T&gt; 时缺少 System

相关文章