Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for missing properties with JSON.net

Tags:

c#

json.net

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 to have a default value when missing in the json.

I tried DefaultValue attribute but it's doesn't work. I'm using private setters and constructor to deserialize the json, so setting the value of the property in the constructor will not work as there is a parameter with the value.

Following is an example:

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

I expect the age to be 5 but it is zero.

Any suggestions?

like image 625
somdoron Avatar asked Apr 13 '15 17:04

somdoron


3 Answers

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

like image 96
somdoron Avatar answered Nov 07 '22 19:11

somdoron


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. 
}
like image 36
Tono Nam Avatar answered Nov 07 '22 21:11

Tono Nam


Add [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] ,Change your Age property from

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

to

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
    [DefaultValue(5)]
    public string Age { get; private set; }
like image 3
Karthikeyan VK Avatar answered Nov 07 '22 20:11

Karthikeyan VK