16

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!

1
  • Please refer to my answer here Commented Nov 9, 2017 at 14:23

3 Answers 3

31

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

if(obj["proprty_name"] != null){
    // do something
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

He's using Newtonsoft.Json not System.Json
-3

Use this JToken.ContainsKey() This should work.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.