Default value for missing properties with JSON.net

前端 未结 2 1315
无人共我
无人共我 2020-12-01 06:07

I\'m using Json.net to serialize objects to database.

I added a new property to the class (which is missing in the json in the database) and I want the new property

相关标签:
2条回答
  • 2020-12-01 06:22

    I found the answer, just need to add the following attribute as well:

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
    

    In your example:

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

    See Json.Net Reference

    0 讨论(0)
  • 2020-12-01 06:36

    You can also have a default value as:

    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. 
    }
    
    0 讨论(0)
提交回复
热议问题