JSON.net缺少属性的默认值 [英] Default value for missing properties with JSON.net

查看:174
本文介绍了JSON.net缺少属性的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

我尝试了DefaultValue属性,但是它不起作用.我使用私有的setter和构造函数对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.

以下是一个示例:

    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岁,但为零.

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

有什么建议吗?

推荐答案

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

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

[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参考

这篇关于JSON.net缺少属性的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆