问题描述
我使用 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 反序列化时会忽略我的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!