• C# 解析获取到JSON


    此处用到了 Newtonsoft.Json 这个DLL文件.因为里面已经封装了很多方法.
    具体下载地址 : http://files.cnblogs.com/cgdou/Json50r8.zip

    里面包含了.NET 框架的各个版本.这里,我用到的是 .NET 4.0

    解析JSON有两种方式,下面将会把代码贴出来.

    先导入命名空间:

    using Newtonsoft.Json;
    using System.Web;
    using Newtonsoft.Json.Linq;
    

    第一种方法:

      反序列化JSON字符串,将JSON字符串转换成LIST列表   

      先定义一个类,类中变量和返回的JSON字段值一样:

      

     public class Customer
        {
     
            //在序列化前后没有变动     
            public string Productid
            { get; set; }
            //在序列化前后设置和重置     
            public string Productname
            { get; set; }
            //设置为null,但在序列化后填充     
            public string Price
            { get; set; }
             public string num
            { get; set; }
            //设置为null,但在序列化后填充     
            public string url
            { get; set; }
    
            public string Other
            { get; set; }
            public Customer()
            {
                //     
                //TODO: 在此处添加构造函数逻辑     
                //     
                Productid = "";
                Productname = "";
                Price = "";
                num = "";
                url = "";
                Other = null;
            }
        }  
    

      然后是解析的方法:

            void GetListJson()
            {
               // string jsonText = "[{'Productid':'1','Productname': '手机','Price':25.5,'num': 1000,'url':'http://www.baidu.com'}]";
                string jsonText = "[{"Productid":1,"Productname": "手机","Price":25.5,"num": 1000,"url":"http://www.baidu.com"}]";
                List<Customer> _list = JsonConvert.DeserializeObject<List<Customer>>(jsonText);
                //读取列表中的值   
                // Console.WriteLine(_list[1].status);
    
                for (int i = 0; i < _list.Count; i++)
                {
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("Productid: " + _list[i].Productid);
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("Productname: " + _list[i].Productname);
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("Price: " + _list[i].Price);
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("num: " + _list[i].num);
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("url: " + _list[i].url);
                }
            }
    

      以后是第一 种,解析比较简单的JSON可以,但如果碰到JSON里面嵌套JSON的情况是,就要用下面这种方法:

     String jsonText = "[{"status":"1","postPrice":[{"Productid":1,"Productname": "手机","Price":25.5,"num": 1000,"url":"http://www.baidu.com"}]}]";
    

      方法如下:

      

            void GetJArryJson()
            {
    
                String jsonText = "[{"status":"1","postPrice":[{"Productid":1,"Productname": "手机","Price":25.5,"num": 1000,"url":"http://www.baidu.com"}]}]";
    
                JArray jsonarray = (JArray)JsonConvert.DeserializeObject(jsonText);
    
                JArray onearray = null;
    
                for (int i = 0; i < jsonarray.Count; i++)
                {
                    TXT_Info.AppendText("	
    ");
                    JObject jsonobject = (JObject)jsonarray[0];
                    TXT_Info.AppendText("status: " + jsonobject["status"].ToString());
                    TXT_Info.AppendText("	
    ");
                    onearray = (JArray)jsonobject["postPrice"];
                    for (int j = 0; j < onearray.Count; j++)
                    {
                        TXT_Info.AppendText("postPrice: ");
                        TXT_Info.AppendText("	
    ");
                        JObject oneobject = (JObject)(onearray[0]);
    
                        TXT_Info.AppendText("	Productid: " + oneobject["Productid"].ToString());
                        TXT_Info.AppendText("	
    ");
                        TXT_Info.AppendText("	Productname: " + oneobject["Productname"].ToString());
                        TXT_Info.AppendText("	
    ");
                        TXT_Info.AppendText("	Price: " + oneobject["Price"].ToString());
                        TXT_Info.AppendText("	
    ");
                        TXT_Info.AppendText("	num: " + oneobject["num"].ToString());
                        TXT_Info.AppendText("	
    ");
                        TXT_Info.AppendText("	url: " + oneobject["url"].ToString());
                        TXT_Info.AppendText("	
    ");
                    }
    
                }
            }
    

      这样.基本上就可以将返回来的JSON进行解析了.

      下面是一种生产环境下会碰到的情况,调用远程REST来获取JSON:

      方法如下,这里使用了第一种方法,将JSON转到List:

      

            void GetCityListJson(String Pcode)
            {
                HttpURL = "http://localhost:8060/MyRest/CommonMethodResource/jsonCity/" + Pcode;
                urlvalue = HttpWebResponseUtility.CreateGetHttpResponse(HttpURL, null, null, null, "utf-8");
                // 开始获取REST的加密信息
                if (urlvalue.Length > 5)
                {
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("获取值成功");
                }
                else
                {
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("获取值失败");
                    return;
                }
    
                List<JsonCity> _list = JsonConvert.DeserializeObject<List<JsonCity>>(urlvalue);
                //读取列表中的值   
                // Console.WriteLine(_list[1].status);
    
                for (int i = 0; i < _list.Count; i++)
                {
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("City_Code: " + _list[i].City_Code);
                    TXT_Info.AppendText("	
    ");
                    TXT_Info.AppendText("City: " + _list[i].City);
                }
            }

      相对应的类:

        public class JsonCity
        {
    
            //在序列化前后没有变动     
            public string City_Code
            { get; set; }
            //在序列化前后设置和重置     
            public string City
            { get; set; }
    
            public JsonCity()
            {
                //     
                //TODO: 在此处添加构造函数逻辑     
                //     
                City_Code = "";
                City = "";
    
            }
        }  
    

      以下是我解析HTTP请求用到的类文件:

      

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.Net;
    using System.IO;
    using System.IO.Compression;
    using System.Text.RegularExpressions;  
    
    
    namespace REST
    {
        class HttpWebResponseUtility
        {
            private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            /// <summary>   
            /// 创建GET方式的HTTP请求   
            /// </summary>   
            /// <param name="url">请求的URL</param>   
            /// <param name="timeout">请求的超时时间</param>   
            /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>   
            /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>   
            /// <returns></returns>   
            public static string CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies, string type)
            {
                try
                {
                    if (string.IsNullOrEmpty(url))
                    {
                        throw new ArgumentNullException("url");
                    }
                    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                    request.Method = "GET";
                    request.UserAgent = DefaultUserAgent;
                    if (!string.IsNullOrEmpty(userAgent))
                    {
                        request.UserAgent = userAgent;
                    }
                    if (timeout.HasValue)
                    {
                        request.Timeout = timeout.Value;
                    }
                    if (cookies != null)
                    {
                        request.CookieContainer = new CookieContainer();
                        request.CookieContainer.Add(cookies);
                    }
                    System.IO.Stream respStream = (request.GetResponse() as HttpWebResponse).GetResponseStream();
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                    {
                        return reader.ReadToEnd();
                    }
                }
                catch (System.Exception ex)
                {
                    //errorMsg = ex.Message;
                }
                return "";
            }
            /// <summary>   
            /// 创建POST方式的HTTP请求   
            /// </summary>   
            /// <param name="url">请求的URL</param>   
            /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>   
            /// <param name="timeout">请求的超时时间</param>   
            /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>   
            /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>   
            /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>   
            /// <returns></returns>   
            public static string CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout,
                string userAgent, Encoding requestEncoding, CookieCollection cookies, string type)
            {
                try
                {
                    if (string.IsNullOrEmpty(url))
                    {
                        throw new ArgumentNullException("url");
                    }
                    if (requestEncoding == null)
                    {
                        throw new ArgumentNullException("requestEncoding");
                    }
                    HttpWebRequest request = null;
                    //如果是发送HTTPS请求   
                    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                    {
                        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                        request = WebRequest.Create(url) as HttpWebRequest;
                        request.ProtocolVersion = HttpVersion.Version10;
                    }
                    else
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                    }
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
    
                    if (!string.IsNullOrEmpty(userAgent))
                    {
                        request.UserAgent = userAgent;
                    }
                    else
                    {
                        request.UserAgent = DefaultUserAgent;
                    }
    
                    if (timeout.HasValue)
                    {
                        request.Timeout = timeout.Value;
                    }
                    if (cookies != null)
                    {
                        request.CookieContainer = new CookieContainer();
                        request.CookieContainer.Add(cookies);
                    }
                    //如果需要POST数据   
                    if (!(parameters == null || parameters.Count == 0))
                    {
                        StringBuilder buffer = new StringBuilder();
                        int i = 0;
                        foreach (string key in parameters.Keys)
                        {
                            if (i > 0)
                            {
                                buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                            }
                            else
                            {
                                buffer.AppendFormat("{0}={1}", key, parameters[key]);
                            }
                            i++;
                        }
                        byte[] data = requestEncoding.GetBytes(buffer.ToString());
                        using (Stream stream = request.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }
                    }
                    System.IO.Stream respStream = (request.GetResponse() as HttpWebResponse).GetResponseStream();
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                    {
                        return reader.ReadToEnd();
                    }
                }
                catch (System.Exception ex)
                {
                    //errorMsg = ex.Message;
                }
                return "";
            }
    
            private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                return true; //总是接受   
            }  
    
        }
    }
    

      以上,就是我用来解析 JSON 的方法了.

  • 相关阅读:
    angularjs---select使用---默认值及联动
    protobuf--嵌套repeated get set
    protobuf--repeated get set
    Spring学习笔记1——基础知识
    Spring的BeanFactoryPostProcessor和BeanPostProcessor
    Git分支管理策略
    如何高效利用 GitHub
    一张思维导图教你使用google一下
    手把手教你如何加入到github的开源世界
    Spring4 MVC HelloWorld 注解和JavaConfig实例
  • 原文地址:https://www.cnblogs.com/cgdou/p/3506258.html
Copyright © 2020-2023  润新知