Jacobian
Jacobian

Reputation: 10802

How to check whether json object has some property

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!

Upvotes: 16

Views: 46118

Answers (3)

karthik loganathan
karthik loganathan

Reputation: 61

Use this JToken.ContainsKey() This should work.

Upvotes: -3

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

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

Upvotes: 8

Maraboc
Maraboc

Reputation: 11083

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

if(obj["proprty_name"] != null){
    // do something
}

Upvotes: 30

Related Questions