如果我的回复有关键“错误”,我需要处理错误并显示警告框。
json.net中是否存在“haskey”方法? 喜欢:
var x= JObject.Parse(string_my);
if(x.HasKey["error_msg"])
MessageBox.Show("Error!")
答案 0 :(得分:217)
只需使用x["error_msg"]
即可。如果该属性不存在,则返回null
。
答案 1 :(得分:90)
JObject
实现IDictionary<string, JToken>
,因此您可以使用:
IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))
...或者您可以使用TryGetValue
。它使用显式接口实现实现这两种方法,因此您不能在不先转换为IDictionary<string, JToken>
的情况下使用它们。
答案 2 :(得分:3)
JObject.ContainsKey(string propertyName)
已在11.0.1版本中作为公用方法
文档-https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm