1 /// <summary>
2 /// 从json中获取对应key的value值
3 /// </summary>
4 /// <param name="json字符串"></param>
5 /// <param name="需要取value对应的key"></param>
6 /// <returns></returns>
7 public string GetJsonValue(string strJson , string key)
8 {
9 //测试:
10 //strJson = @"{'1':{'id':{'ip':'192.168.0.1','p':34,'pass':'ff','port':80,'user':'t'}},'code':0}";
11 //key = "user"
12 string strResult="";
13 JObject jsonObj = JObject.Parse(strJson);
14 strResult = GetNestJsonValue(jsonObj.Children(), key);
15 return strResult;
16 }
17 /// <summary>
18 /// 迭代获取eky对应的值
19 /// </summary>
20 /// <param name="jToken"></param>
21 /// <param name="key"></param>
22 /// <returns></returns>
23 public string GetNestJsonValue(JEnumerable<JToken> jToken, string key)
24 {
25 IEnumerator enumerator = jToken.GetEnumerator();
26 while (enumerator.MoveNext())
27 {
28 JToken jc = (JToken)enumerator.Current;
29 if (jc is JObject || ((JProperty)jc).Value is JObject)
30 {
31 return GetNestJsonValue(jc.Children(), key);
32 } else
33 {
34 if (((JProperty)jc).Name == key)
35 {
36 return ((JProperty)jc).Value.ToString();
37 }
38 }
39 }
40 return null;
41 }