Why when I deserialize with JSON.NET ignores my default value?(为什么当我使用 JSON.NET 反序列化时会忽略我的默认值?)
问题描述
我使用 JSON.NET 作为我的主要序列化程序.
I'm using JSON.NET as my main serializer.
这是我的模型,看我设置了一些 JSONProperties 和一个 DefaultValue.
This is my model, look that I've setted some JSONProperties and a DefaultValue.
public class AssignmentContentItem
{
[JsonProperty("Id")]
public string Id { get; set; }
[JsonProperty("Qty")]
[DefaultValue(1)]
public int Quantity { get; set; }
}
当我序列化一个 List 时,它做得很好:
When I serialize a List<AssignmentContentItem>, it doing a good work:
private static JsonSerializerSettings s = new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
输出:
[{"Id":"Q0"},{"Id":"Q4"},{"Id":"Q7"}]
但是当我想反序列化这个 jsonContent 时,属性 Qty 总是 0 并且没有设置为默认值.我的意思是,当我反序列化 jsonContent 时,数量的 DefaultValue 应该是 1 而不是 0.
But when I'd like to deserialize this jsonContent, the property Qty is always 0 and is not set to the default value. I mean, when I deserialize that jsonContent, as DefaultValue for Quantity should be one instead of 0.
public static List<AssignmentContentItem> DeserializeAssignmentContent(string jsonContent)
{
return JsonConvert.DeserializeObject<List<AssignmentContentItem>>(jsonContent, s);
}
我该怎么办
推荐答案
DefaultValue 属性没有设置属性的值.看到这个问题:.NET DefaultValue 属性
The DefaultValue attribute does not set the value of the property. See this question: .NET DefaultValue attribute
最好在构造函数中设置值:
What you might be better off doing is setting the value in the constructor:
public class AssignmentContentItem
{
[JsonProperty("Id")]
public string Id { get; set; }
[JsonProperty("Qty")]
public int Quantity { get; set; }
public AssignmentContentItem()
{
this.Quantity = 1;
}
}
这一行在哪里:
AssignmentContentItem item =
JsonConvert.DeserializeObject<AssignmentContentItem>("{"Id":"Q0"}");
导致 AssignmentContentItem 的 Quantity 设置为 1.
Results in an AssignmentContentItem with its Quantity set to 1.
这篇关于为什么当我使用 JSON.NET 反序列化时会忽略我的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么当我使用 JSON.NET 反序列化时会忽略我的默认值?
- 使用 rss + c# 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
