Default value for missing properties with JSON.net(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 属性,但它不起作用.我正在使用私有设置器和构造器来反序列化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 中缺少的属性的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JSON.net 中缺少的属性的默认值


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01