15

In Java there is a nice method has that makes it possible to check whether a json object contains a key or not. I use it like so:

JSONObject obj = ....; // <- got by some procedure
if(obj.has("some_key")){
    // do something
}

I could not find the same cool functionality in newtonsoft.json library for C#. So, I wonder what are the alternatives. Thanks!

Jacobian
  • 10,122
  • 29
  • 128
  • 221

3 Answers3

26

Just use obj["proprty_name"]. If the property doesn't exist, it returns null

if(obj["proprty_name"] != null){
    // do something
}
Maraboc
  • 10,550
  • 3
  • 37
  • 48
8

You can try like this:

IDictionary<string, JToken> dict = x;
if (dict.ContainsKey("some_key"))

since JSONObject implements IDictionary<string, JToken>. You can refer MSDN for details

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
-2

Use this JToken.ContainsKey() This should work.