json提取多层嵌套到数组,json提取嵌套数据

//数据
string html = “{\”code\”:\”0000\”,\”desc\”:\”\”,\”data\”:
{\”token\”: \”1234567899654\”}}”;
//解析
JsonObject jo = (JsonObject)SimpleJson.DeserializeObject(html);
string code = jo[“code”].ToString();
if (code.Equals(“0000”))
{
JsonObject jar = (JsonObject)
SimpleJson.DeserializeObject(jo[“data”].ToString());
string token = jar[“token”].ToString();
}

json比相似格式再复杂点的就如数组一样,有多层嵌套,商量了弹指间,记录代码如下:

using Newtonsoft.Json.Linq;

  1. [csharp] view
    plain copy
     

    1. using AIOWeb.Models;  
    2. using Newtonsoft.Json;  
    3. using Newtonsoft.Json.Linq;  
    4. using System;  
    5. using System.Collections.Generic;  
    6. using System.Data;  
    7. using System.Data.SqlClient;  
    8. using System.Linq;  
    9. using System.Web;  
    10.   
    11. namespace AIOWeb  
    12. {  
    13.     /// <summary>  
    14.     /// wxapi 的摘要表达  
    15.     /// </summary>  
    16.     public class wxapi : IHttpHandler  
    17.     {  
    18.         public void ProcessRequest(HttpContext context)  
    19.         {  
    20.             context.Response.ContentType = “text/plain”;  
    21.   
    22.             string code = “”;  
    23. json提取多层嵌套到数组,json提取嵌套数据。            string iv = “”;  
    24.             string encryptedData = “”;  
    25.             try  
    26.             {  
    27.                 code = HttpContext.Current.Request.QueryString[“code”].ToString();  
    28.                 iv = HttpContext.Current.Request.QueryString[“iv”].ToString();  
    29.                 encryptedData = HttpContext.Current.Request.QueryString[“encryptedData”].ToString();  
    30.             }  
    31.             catch (Exception ex)  
    32.             {  
    33.                 context.Response.Write(ex.ToString());  
    34.             }  
    35.   
    36.             string Appid = “wxdb2641f85b04f1b3”;  
    37.             string Secret = “8591d8cd7197b9197e17b3275329a1e7”;  
    38.             string grant_type = “authorization_code”;  
    39.   
    40.             //向微信服务端 使用登录凭证 code 获取 session_key 和 openid   
    41.             string url = “” + Appid + “&secret=” + Secret + “&js_code=” + code + “&grant_type=” + grant_type;  
    42.             string type = “utf-8”;  
    43.   
    44.             AIOWeb.Models.GetUsersHelper GetUsersHelper = new AIOWeb.Models.GetUsersHelper();  
    45.             string j = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器重临字符串  
    46.   
    47.             //将字符串转换为json格式  
    48.             JObject jo = (JObject)JsonConvert.DeserializeObject(j);  
    49.   
    50.             result res = new result();  
    51.             try  
    52.             {  
    53.                 //微信服务器验证成功  
    54.                 res.openid = jo[“openid”].ToString();  
    55.                 res.session_key = jo[“session_key”].ToString();  
    56.             }  
    57.             catch (Exception)  
    58.             {  
    59.                 //微信服务器验证失败  
    60.                 res.errcode = jo[“errcode”].ToString();  
    61.                 res.errmsg = jo[“errmsg”].ToString();  
    62.             }  
    63.             if (!string.IsNullOrEmpty(res.openid))  
    64.             {  
    65.                 //用户数据解密  
    66.                 GetUsersHelper.AesIV = iv;  
    67.                 GetUsersHelper.AesKey = res.session_key;  
    68.   
    69.                 string result = GetUsersHelper.AESDecrypt(encryptedData);  
    70.   
    71.   
    72.                 //存款和储蓄用户数量  
    73.                 JObject _usrInfo = (JObject)JsonConvert.DeserializeObject(result);  
    74.   
    75.                 userInfo userInfo = new userInfo();  
    76.                 userInfo.openId = _usrInfo[“openId”].ToString();  
    77.   
    78.                 try //部分验证重返值中尚无unionId  
    79.                 {  
    80.                     userInfo.unionId = _usrInfo[“unionId”].ToString();  
    81.                 }  
    82.                 catch (Exception)  
    83.                 {  
    84.                     userInfo.unionId = “unionId”;  
    85.                 }  
    86.                   
    87.                 userInfo.nickName = _usrInfo[“nickName”].ToString();  
    88.                 userInfo.gender = _usrInfo[“gender”].ToString();  
    89.                 userInfo.city = _usrInfo[“city”].ToString();  
    90.                 userInfo.province = _usrInfo[“province”].ToString();  
    91.                 userInfo.country = _usrInfo[“country”].ToString();  
    92.                 userInfo.avatarUrl = _usrInfo[“avatarUrl”].ToString();  
    93.   
    94.                 object watermark = _usrInfo[“watermark”].ToString();  
    95.                 object appid = _usrInfo[“watermark”][“appid”].ToString();  
    96.                 object timestamp = _usrInfo[“watermark”][“timestamp”].ToString();  
    97.  
    98.  
    99.                 #region  
    100.   
    101.   
    102.                 //创造连接池对象(与数据库服务器进行连接)  
    103.                 SqlConnection conn = new SqlConnection(“server=127.0.0.1;database=Test;uid=sa;pwd=1”);  
    104.                 //打开连接池  
    105.                 conn.Open();  
    106.                 //创设命令对象  
    107.                 string Qrystr = “SELECT * FROM WeChatUsers WHERE openId='” + userInfo.openId + “‘”;  
    108.                 SqlCommand cmdQry = new SqlCommand(Qrystr, conn);  
    109.                 object  obj = cmdQry.ExecuteScalar();  
    110.                 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))  
    111.                 {  
    112.                     string str = “INSERT INTO WeChatUsers ([UnionId] ,[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],[Timestamp],[Memo],[counts])VALUES(‘” + userInfo.unionId + “‘,'” + userInfo.openId + “‘,'” + userInfo.nickName + “‘,'” + userInfo.gender + “‘,'” + userInfo.city + “‘,'” + userInfo.province + “‘,'” + userInfo.country + “‘,'” + userInfo.avatarUrl + “‘,'” + appid.ToString() + “‘,'” + timestamp.ToString() + “‘,’来自微信小程序’,’1′)”;  
    113.   
    114.                     SqlCommand cmdUp = new SqlCommand(str, conn);  
    115.                     // 执行操作  
    116.                     try  
    117.                     {  
    118.                         int row = cmdUp.ExecuteNonQuery();  
    119.                     }  
    120.                     catch (Exception ex)  
    121.                     {  
    122.                         context.Response.Write(ex.ToString());  
    123.                     }  
    124.                 }  
    125.                 else  
    126.                 {  
    127.                     //多次访问,记录走访次数counts   更新unionId是防止最初并未有,中期关联后却仍未记录  
    128.                     string str = “UPDATE dbo.WeChatUsers SET counts = counts+1,UnionId = ‘” + userInfo.unionId + “‘ WHERE OpenId='” + userInfo.openId + “‘”;  
    129.                     SqlCommand cmdUp = new SqlCommand(str, conn);  
    130.                     int row = cmdUp.ExecuteNonQuery();  
    131.                 }  
    132.                  
    133.                 //关闭连接池  
    134.                 conn.Close();  
    135.                 #endregion  
    136.   
    137.                 //重返解密后的用户数据  
    138.                 context.Response.Write(result);  
    139.             }  
    140.             else  
    141.             {  
    142.                 context.Response.Write(j);  
    143.             }  
    144.         }  
    145.   
    146.         public bool IsReusable  
    147.         {  
    148.             get  
    149.             {  
    150.                 return false;  
    151.             }  
    152.         }  
    153.     }  
    154. }  

  string jsonText = “{‘name’:’test’,’phone’:’18888888888′,’image’:[{‘name’:’img1′,’data’:’data1′},{‘name’:’img2′,’data’:’data2′},{‘name’:’img3′,’data’:’data3′}]}”;

using Newtonsoft.Json;

 

 

 

GetUsersHelper 帮助类

 

**\[csharp\]** [view
plain](http://blog.csdn.net/qq954637101/article/details/60960044) [copy](http://blog.csdn.net/qq954637101/article/details/60960044)
 

1.  using System;  
2.  using System.Collections.Generic;  
3.  using System.IO;  
4.  using System.Linq;  
5.  using System.Security.Cryptography;  
6.  using System.Text;  
7.  using System.Threading.Tasks;  
8.    
9.  namespace AIOWeb.Models  
10. {  
11.     public class GetUsersHelper  
12.     {  
13.   
14.         /// &lt;summary&gt;  
15.         /// 获取链接返回数据  
16.         /// &lt;/summary&gt;  
17.         /// &lt;param name="Url"&gt;链接&lt;/param&gt;  
18.         /// &lt;param name="type"&gt;请求类型&lt;/param&gt;  
19.         /// &lt;returns&gt;&lt;/returns&gt;  
20.         public  string GetUrltoHtml(string Url, string type)  
21.         {  
22.             try  
23.             {  
24.                 System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);  
25.                 // Get the response instance.  
26.                 System.Net.WebResponse wResp = wReq.GetResponse();  
27.                 System.IO.Stream respStream = wResp.GetResponseStream();  
28.                 // Dim reader As StreamReader = New StreamReader(respStream)  
29.                 using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))  
30.                 {  
31.                     return reader.ReadToEnd();  
32.                 }  
33.             }  
34.             catch (System.Exception ex)  
35.             {  
36.                 return ex.Message;  
37.             }  
38.         }  
39.         \#region 微信小程序用户数据解密  
40.   
41.         public static string AesKey;  
42.         public static string AesIV;  
43.   
44.         /// &lt;summary&gt;  
45.         /// AES解密  
46.         /// &lt;/summary&gt;  
47.         /// &lt;param name="inputdata"&gt;输入的数据encryptedData&lt;/param&gt;  
48.         /// &lt;param name="AesKey"&gt;key&lt;/param&gt;  
49.         /// &lt;param name="AesIV"&gt;向量128&lt;/param&gt;  
50.         /// &lt;returns name="result"&gt;解密后的字符串&lt;/returns&gt;  
51.         public string AESDecrypt(string inputdata)  
52.         {  
53.             try  
54.             {  
55.                 AesIV = AesIV.Replace(" ", "+");  
56.                 AesKey = AesKey.Replace(" ", "+");  
57.                 inputdata = inputdata.Replace(" ", "+");  
58.                 byte\[\] encryptedData = Convert.FromBase64String(inputdata);  
59.   
60.                 RijndaelManaged rijndaelCipher = new RijndaelManaged();  
61.                 rijndaelCipher.Key = Convert.FromBase64String(AesKey); // Encoding.UTF8.GetBytes(AesKey);  
62.                 rijndaelCipher.IV = Convert.FromBase64String(AesIV);// Encoding.UTF8.GetBytes(AesIV);  
63.                 rijndaelCipher.Mode = CipherMode.CBC;  
64.                 rijndaelCipher.Padding = PaddingMode.PKCS7;  
65.                 ICryptoTransform transform = rijndaelCipher.CreateDecryptor();  
66.                 byte\[\] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);  
67.                 string result = Encoding.UTF8.GetString(plainText);  
68.   
69.                 return result;  
70.             }  
71.             catch (Exception)  
72.             {  
73.                 return null;  
74.   
75.             }  
76.         }  
77.         \#endregion  
78.     }  
79. }  

  JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);

亚洲必赢官网, 

  string zone = jo[“name”].ToString();

JObject json = (JObject)JsonConvert.DeserializeObject(json);

  string zone_en = jo[“phone”].ToString();

 

  JArray jar = JArray.Parse(jo[“image”].ToString());

 

  MessageBox.Show(zone);

JObject monitorinfo =
(JObject)JsonConvert.DeserializeObject(responseContent);
JArray jar = JArray.Parse(monitorinfo[“data”].ToString());
string emsg = string.Empty;

  MessageBox.Show(zone_en);

mod.Success = Convert.ToBoolean(monitorinfo[“success”]) ? 1 : 0;
if (mod.Success == 0)
{
mod.ReasonCode = monitorinfo[“reason_code”].ToString();
mod.ReasonDesc = monitorinfo[“reason_desc”].ToString();
}

  for (var i = 0; i < jar.Count; i++)

 

  {   

modBLACKLIST mod1 =
JsonConvert.DeserializeObject<modBLACKLIST>(risklist[j].ToString());

         JObject j = JObject.Parse(jar[i].ToString());

 

        MessageBox.Show(j[“name”].ToString());

public class modGREYLIST : modCommonField
{
public string evidence_type { get; set; }
public string risk_level { get; set; }
public JArray risk_type { get; set; }
public string monitor_field_zh { get; set; }
public string evidence_type_zh { get; set; }
public string risk_level_zh { get; set; }
public JArray risk_type_zh { get; set; }
}

        MessageBox.Show(j[“data”].ToString());

  }

关键便是使用了JArray.Parse。

网站地图xml地图