为什么当我JSON.NET反序列化无视我的默认值? [英] Why when I deserialize with JSON.NET ignores my default value?
问题描述
我用JSON.NET作为我的主要串行器。
I'm using JSON.NET as my main serializer.
这是我的模型,看,我已经设置好的一些 JSONProperties
和默认值
。
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; }
}
当我序列化列表< AssignmentContentItem>
,它做了很好的工作:
When I serialize a List<AssignmentContentItem>
, it doing a good work:
private static JsonSerializerSettings s = new JsonSerializerSettings
{ DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore };
OUTPUT:
OUTPUT:
[{ID:Q0},{ID:第四季度},{ID:Q7}]
[{"Id":"Q0"},{"Id":"Q4"},{"Id":"Q7"}]
但是,当我想反序列化这个jsonContent,财产数量始终为0,而不是设置为默认值。我的意思是,当我反序列化jsonContent,作为默认值的数量应该有一个而不是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);
}
我应该怎么办
What should I do
推荐答案
的默认值
属性不设置该属性的值。看到这个问题: .NET默认值属性
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;
}
}
这条线:
Where this line:
AssignmentContentItem item =
JsonConvert.DeserializeObject<AssignmentContentItem>("{\"Id\":\"Q0\"}");
结果在 AssignmentContentItem
与数量
设置为 1
。
这篇关于为什么当我JSON.NET反序列化无视我的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!