156

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!")
SevenDays
  • 3,718
  • 10
  • 44
  • 71
  • 1
    Please refer to my answer [here](https://stackoverflow.com/a/47204235/1037314). – Ben Nov 09 '17 at 14:24
  • I answered a question with similar problem in here: https://stackoverflow.com/a/47204235/1037314 – Ben Nov 09 '17 at 14:33
  • 1
    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 Feb 19 '18 at 15:55

4 Answers4

277

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

svick
  • 236,525
  • 50
  • 385
  • 514
  • 46
    What if the value of the property is `null`? – Andreas Furster Mar 04 '15 at 14:34
  • 77
    @AndreasFurster Then it will return a `JValue` whose `Value` is `null`, not just `null`. – svick Mar 04 '15 at 16:45
  • 2
    If the property could be `null` you could use `x["error_msg"] is Object` to check if the property is defined in JSON object – stonito Nov 15 '16 at 14:24
  • 2
    @user3199329 That's just a confusing way to write `x["error_msg"] != null`, so no, it does not check that the property exists and has the value of `null`. – svick Nov 15 '16 at 14:40
  • Keep in mind that if you're checking for the existence of a nested token you have to check each level separately. For example `myJObject["level1property"]["level2property"]` with throw if `level1property` doesn't exist. You must check `myJObject["level1property"]` first. – William T. Mallard Jan 04 '17 at 18:53
  • 9
    @WilliamT.Mallard In C# 6, you can simplify that by using the null-conditional index operator: `myJObject["level1property"]?["level2property"]`. – svick Jan 04 '17 at 19:45
  • @svick Thanks! I suppose at some point you'll be able to toss a question mark pretty much anywhere in your code. :) – William T. Mallard Jan 04 '17 at 20:02
  • this will give exception 'System.NullReferenceException: Object reference not set to an instance of an object.' if 'error_msg' not present in x – TejpalBh Jun 22 '19 at 05:41
104

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I thin this will be slowly then the accepted answer, but thanks. – SevenDays Aug 27 '11 at 21:46
  • 2
    @wsevendays, does speed matter to you here or are just microoptimizing (and basing that on guesses)? You should use what you find more readable. – svick Aug 27 '11 at 21:57
  • The speed of 1GHz processor of my WP7 phone not great and I need to care about speed. – SevenDays Aug 27 '11 at 22:21
  • 1
    @wsevendays: Why would it be slower (or faster) than the accepted answer? – Jon Skeet Aug 28 '11 at 02:19
  • Your method creates the dictionary, it will be slower from the start.An Accepted answer method only checks if key is in array. – SevenDays Aug 28 '11 at 22:22
  • 25
    @wsevenday: No, it doesn't *create* a dictionary. `JObject` *already implements* `IDictionary`. This is *just* a reference assignment. And no, the accepted answer isn't checking if the key is in an *array*... it's still using a normal indexer. Just because it *looks* like array access doesn't mean it *is* array access. (Array access can't be by a string in the first place.) – Jon Skeet Aug 29 '11 at 07:10
  • Calling a method via an abstract interface such as IDictionary is slower than calling it via the public interface, but we're talking about a ridiculously tiny amount. – Jonathan Allen Jan 07 '17 at 05:42
17

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

Blue
  • 22,608
  • 7
  • 62
  • 92
Razor
  • 669
  • 1
  • 10
  • 28
0

doing something like below is useful, if key is absent it submits Null into db. Using ?? and DBNull help fix the issue

eachObject is of type JToken
DataRow dr = localTable.NewRow();                   
dr["Campaign_ID"] = (object)eachObject["id"] ?? DBNull.Value;
dr["Campaign_Name"] = (object)eachObject["name"] ?? DBNull.Value;
dr["Campaign_Subject"] = (object)eachObject["subject"] ?? DBNull.Value;