C# 獲取json中某key對應的值,支援迭代
阿新 • • 發佈:2018-10-31
/// <summary> /// 從json中獲取對應key的value值 /// </summary> /// <param name="json字串"></param> /// <param name="需要取value對應的key"></param> /// <returns></returns> public string GetJsonValue(string strJson , string key) { //測試: //strJson = @"{'1':{'id':{'ip':'192.168.0.1','p':34,'pass':'ff','port':80,'user':'t'}},'code':0}"; //key = "user" string strResult=""; JObject jsonObj = JObject.Parse(strJson); strResult = GetNestJsonValue(jsonObj.Children(), key); return strResult; } /// <summary> /// 迭代獲取eky對應的值 /// </summary> /// <param name="jToken"></param> /// <param name="key"></param> /// <returns></returns> public string GetNestJsonValue(JEnumerable<JToken> jToken, string key) { IEnumerator enumerator = jToken.GetEnumerator(); while (enumerator.MoveNext()) { JToken jc = (JToken)enumerator.Current; if (jc is JObject || ((JProperty)jc).Value is JObject) { return GetNestJsonValue(jc.Children(), key); } else { if (((JProperty)jc).Name == key) { return ((JProperty)jc).Value.ToString(); } } } return null; }