【问题标题】:Ignore some of the properties during Json.NET serializing but required on others在 Json.NET 序列化期间忽略某些属性,但在其他属性上是必需的
【发布时间】:2020-08-10 08:41:06
【问题描述】:

我正在使用 Json.Net 来序列化一个对象。 这是代码:

 var jsonText = JsonConvert.SerializeObject(objectToSerialize, Formatting.Indented,
                    new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });

DefaultValueHandling 设置为忽略,因此结果字符串不包含具有默认值的属性。

在 Serialized 类中,无论如何都有一个唯一的属性应该在结果字符串上, 所以我使用一个属性来确保该属性将在那里:

[JsonProperty(PropertyName = "componentMainVersion", Required = Required.Always)] 
    public ushort Version { get; set; }

问题是属性没有生成到字符串。 将字符串反序列化回对象时出现异常:

"Newtonsoft.Json.Schema.JsonSchemaException: '必需的属性是 对象中缺少:版本..."

我怎样才能确保该属性无论如何都会在结果字符串中(默认值与否)?

【问题讨论】:

    标签: c# json serialization json.net


    【解决方案1】:

    试试下面的代码

        [JsonProperty(PropertyName = "componentMainVersion", DefaultValueHandling = DefaultValueHandling.Include)] 
        public ushort Version { get; set; }
    

    Required 是一个不同的属性,它确保该属性的值始终是必需的

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 2013-08-17
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      相关资源
      最近更新 更多