Reputation: 987
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.
Upvotes: 9
Views: 21685
Reputation: 987
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;}
Upvotes: 18
Reputation: 518
I think you are looking for the DefaultValueAttribute http://james.newtonking.com/projects/json/help/index.html?topic=html/T_Newtonsoft_Json_DefaultValueHandling.htm
Upvotes: 2
Reputation: 247
The real question here is: Why do you want to force the sender to set null on some values? While building an app you can never force users to behave, that's the number 1 window for hacking your app.
Always assume users wont do what you want at some point. If that JSON comes from any other app that you own just make it send null, if its an external app or user input assume anything is possible.
And Required doesn't mean the field is required in the input, it means it requires a value. That's your problem.
Upvotes: 2