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
439 views
in Technique[技术] by (71.8m points)

c# - Deserializing with Json.NET: Requiring a property/key to be present

When using Json.NET to deserialize a JSON string into an object, how do I require a key/property to be present in the JSON stirng, but allow for NULL values?

For example:

Lets say I have a class/object...

[DataContract]
public class Car
{
    [DataMember(IsRequired = true)]
    public string Vin {get; set;}

    [DataMember(IsRequired = true)]
    public string Color {get; set;}

    public string Description {get; ;set}
}

In the above example, the VIN and Color are required, and an exception would be thrown if either one of them is missing from the JSON string. But lets say that whether or not the Description property has a value after being deserialized is optional. In other words NULL is a valid value. There are two ways to make this happen in the JSON string:

1)

{
    "vin": "blahblahblah7",
    "color": "blue",
    "description":  null
}

or 2)

{
    "vin": "blahblahblah7",
    "color": "blue"
}

The problem is that I don't want to assume that the Description value should be NULL just because the key/value pair for the was left out of the JSON string. I want the sender of the JSON to be explicit about setting it to NULL. If scenario #2 were to happen, I want to detect it and respond with an error message. So how do I require the key/value pair to be present, but accept NULL as a value?

If it helps any, I'm trying to solve this problem within the context of an ASP.NET Web API project.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Ugh. I should have spend a little more time in the Json.NET documentation...

The answer is the the Required property of the JsonPropertyAttribute, which is of enum type Newtonsoft.Json.Required

[JsonProperty(Required = Newtonsoft.Json.Required.AllowNull)]
public string Description {get; set;}

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

...