【问题标题】:Default value for missing properties with JSON.netJSON.net 中缺少的属性的默认值
【发布时间】:2015-06-19 02:59:37
【问题描述】:

我正在使用 Json.net 将对象序列化到数据库。

我向类中添加了一个新属性(数据库中的 json 中缺少该属性),并且我希望新属性在 json 中缺少时具有默认值。

我尝试了 DefaultValue 属性,但它不起作用。我正在使用私有的setter和构造函数来反序列化json,所以在构造函数中设置属性的值将不起作用,因为有一个带有值的参数。

以下是一个例子:

    class Cat
    {
        public Cat(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public string Name { get; private set; }

        [DefaultValue(5)]            
        public int Age { get; private set; }
    }

    static void Main(string[] args)
    {
        string json = "{\"name\":\"mmmm\"}";

        Cat cat = JsonConvert.DeserializeObject<Cat>(json);

        Console.WriteLine("{0} {1}", cat.Name, cat.Age);
    }

我预计年龄是 5 岁,但它是零。

有什么建议吗?

【问题讨论】:

标签: c# json.net


【解决方案1】:

我遇到了与已经描述过的人相同的问题,其中可能存在的构造函数使 DefaultValueHandling 不起作用。我玩了一下,发现可以用 NullValueHandling 绕过。

[DefaultValue(5)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, NullValueHandling = NullValueHandling.Ignore)]
public int Age { get; set; }

【讨论】:

    【解决方案2】:

    添加 [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] ,更改您的 Age 属性

        [DefaultValue(5)]            
        public int Age { get; private set; }
    

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        [DefaultValue(5)]
        public string Age { get; private set; }
    

    【讨论】:

      【解决方案3】:

      你也可以有一个默认值:

      class Cat
      {           
          public string Name { get; set; }
              
          public int Age { get; set; } = 1 ; // one is the default value. If json property does not exist when deserializing the value will be one. 
      }
      

      【讨论】:

        【解决方案4】:

        我找到了答案,只需要添加以下属性:

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        

        在你的例子中:

        class Cat
        {
            public Cat(string name, int age)
            {
                Name = name;
                Age = age;
            }
        
            public string Name { get; private set; }
        
            [DefaultValue(5)]            
            [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
            public int Age { get; private set; }
        }
        
        static void Main(string[] args)
        {
            string json = "{\"name\":\"mmmm\"}";
        
            Cat cat = JsonConvert.DeserializeObject<Cat>(json);
        
            Console.WriteLine("{0} {1}", cat.Name, cat.Age);
        }
        

        Json.Net Reference

        【讨论】:

        • 另一个选项是 IgnoreAndPopulate,它将跳过值与默认值匹配的成员的序列化,这会使您的最终序列化字符串更小。在反序列化时,它就像 Populate 一样工作,如果 JSON 字符串中不存在,则设置默认值。
        猜你喜欢
        • 2021-09-20
        • 2021-06-21
        • 2014-01-04
        • 1970-01-01
        • 2015-02-16
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        相关资源
        最近更新 更多