1. 程式人生 > >C# 獲取json中某key對應的值,支援迭代

C# 獲取json中某key對應的值,支援迭代

        /// <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;
        }

參考https://www.cnblogs.com/feiyuhuo/p/6098065.html