Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

c# - Why when I deserialize with JSON.NET ignores my default value?

I'm using JSON.NET as my main serializer.

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; }
}

When I serialize a List<AssignmentContentItem>, it doing a good work:

private static JsonSerializerSettings s = new JsonSerializerSettings
{
    DefaultValueHandling = DefaultValueHandling.Ignore,
    NullValueHandling = NullValueHandling.Ignore
};

OUTPUT:

[{"Id":"Q0"},{"Id":"Q4"},{"Id":"Q7"}]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"}");

Results in an AssignmentContentItem with its Quantity set to 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...