为什么当我JSON.NET反序列化无视我的默认值? [英] Why when I deserialize with JSON.NET ignores my default value?

查看:187
本文介绍了为什么当我JSON.NET反序列化无视我的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆