Search code examples
c#jsonvalidationjson.net

Newtonsoft JSON, check if property and its value exists


I have an API where I get JSON as an input and I want to check if the specified property and it's value exists in that JSON.

Note: The JSON is not generated from code but is typed by the user so I cannot validate the JSON while serializing.

Consider the following JSON:

{
  "id": 1,
  "someProperties": 
  {
    "property1": "abc",
    "property2": ["zzz", "ccc"]
  }
}

In someProperties, property1 and property2 both can either exists at the same time or anyone of them. So I want to check which all properties are present. And if present, whether that property has the valid value.

I tried the following code:

dynamic request = JsonConvert.DeserializeObject(JSONRequestData);
var X = request["someProperties"]["property1"];

Following are the two scenarios I have to check with their respective responses:

  • If "property1": "abc" is not present in JSON then I am getting null in X
  • If I put property1 in JSON without its value which will look something like this "property1": , then I am getting null.

So how do I differentiate between property not being present in JSON and value of property not being present?


Solution

  • dynamic request = JsonConvert.DeserializeObject(JSONRequestData); always creates a request as JObject, so you can use the methods of JObject. JObject itself implements the IDictionary<string, JToken> interface, which provides the ContainsKey method. So you can simply do

    request.someproperties.ContainsKey("property1");
    

    This will return true only if someproperties contains a property named property1, regardless of it's value. Ie, it doesn't matter if request.someproperties.property1 is null or any type, as long as it is contained in the object.

    See also this fiddle