简体   繁体   中英

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 2 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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM