148
votes

If my response has key "error" I need to process error and show warning box.

Is there "haskey" method exists in json.net? Like:

var x= JObject.Parse(string_my);
if(x.HasKey["error_msg"])
    MessageBox.Show("Error!")
3
Please refer to my answer here. - Ben
I answered a question with similar problem in here: stackoverflow.com/a/47204235/1037314 - Ben
There are two variants of this question: One variant is where JSON dictionary is flat (no children) and another, where key is somewhere in hierarchy of children. At the time of writing this, ns.json still has no convenience method that would give easy access to test for a key. - ljgww

3 Answers

264
votes

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

102
votes

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

15
votes

JObject.ContainsKey(string propertyName) has been made as public method in 11.0.1 release

Documentation - https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm