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 exa
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.
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;}
I think you are looking for the DefaultValueAttribute http://james.newtonking.com/projects/json/help/index.html?topic=html/T_Newtonsoft_Json_DefaultValueHandling.htm