我正在使用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岁但是为零.
有什么建议?
som*_*ron 99
我找到了答案,只需要添加以下属性:
[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参考
你也可以有一个默认值:
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. 
}
| 归档时间: | 
 | 
| 查看次数: | 44171 次 | 
| 最近记录: |