json.net has key method?

C#Jsonjson.net

C# Problem Overview


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!")

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Solution 3 - C#

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

Solution 4 - C#

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;                       

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSevenDaysView Question on Stackoverflow
Solution 1 - C#svickView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#RazorView Answer on Stackoverflow
Solution 4 - C#suntosh aqulaView Answer on Stackoverflow