Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

json.net

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.

like image 768
Kerby Avatar asked Apr 30 '13 04:04

Kerby


1 Answers

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;}
like image 170
Kerby Avatar answered Sep 20 '22 20:09

Kerby