zoukankan      html  css  js  c++  java
  • NewtonSoft.json 序列化和反序列化实例

    在百度 API Store 找个旅游的 API 来当成本次 Demo 的例子

    接口地址:http://apis.baidu.com/apistore/attractions/spot
    AIPKEY: ba491eeaaedf24f4fb20f59e9df27eb6

    先拿到返回的 Json 字符串:

     /// <summary>
        /// 发送HTTP请求
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">请求的参数</param>
        /// <returns>请求结果</returns>
        public static string request(string url, string param)
        {
            string strURL = url + '?' + param;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "GET";
            // 添加header
            request.Headers.Add("apikey", "ba491eeaaedf24f4fb20f59e9df27eb6");
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();
            string StrDate = "";
            string strValue = "";
            StreamReader Reader = new StreamReader(s, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strValue += StrDate + "
    ";
            }
            return strValue;
        }

    调用:

     string url = "http://apis.baidu.com/apistore/attractions/spot";
     string param = "id=yiheyuan&output=json";
     string jsonText = request(url, param);

    使用 Newtonsoft.Json.dll 来进行 Json 的序列化 :

    string json = JsonConvert.DeserializeObject(jsonText).ToString();

    得到的 Json 字符串:

    {
      "error": 0,
      "status": "Success",
      "date": "2015-09-09",
      "result": {
        "name": "颐和园",
        "location": {
          "lng": 116.26844967549,
          "lat": 39.992182483805
        },
        "telephone": "010-62881144",
        "star": "5",
        "url": "http://lvyou.baidu.com/yiheyuan",
        "abstract": "我国现存规模最大、保存最完整的皇家园林,久负盛名。",
        "description": "颐和园位于北京西北郊海淀区内,距北京城区15公里,是我国现存规模最大,保存最完整的皇家园林之一,也是享誉世界的旅游胜地之一。 颐和园是利用昆明湖、万寿山为基址,以杭州西湖风景为蓝本,汲取江南园林的某些设计手法和意境而建成的一座大型天然山水园,也是保存得最完整的一座皇家行宫御苑,被誉为皇家园林博物馆。 颐和园景区规模宏大,园内建筑以佛香阁为中心,园中有景点建筑物百余座、大小院落20余处,3555古建筑,面积70000多平方米,共有亭、台、楼、阁、廊、榭等不同形式的建筑3000多间。古树名木1600余株。其中佛香阁、长廊、石舫、苏州街、十七孔桥、谐趣园、大戏台等都已成为家喻户晓的代表性建筑。",
        "ticket_info": {
          "price": "1. 旺季(4月1日~10月31日):30.00元 德和园:5.00元 佛香阁:10.00元 苏州街:10.00元 文昌院:20.00元 联票(含门票、文昌院、德和园、佛香阁、苏州街澹宁堂):60.00元 2. 淡季(11月1日~3月31日):20.00元 德和园:5.00元 佛香阁:10.00元 苏州街:10.00元 文昌院:20.00元 联票(含门票、文昌院、德和园、佛香阁、苏州街澹宁堂):50.00元",
          "open_time": "1. 旺季(4月1日~10月31日):06:30~20:00 停止售票时间:18:00 园中园(含文昌院、德和园、佛香阁、苏州街澹宁堂):08:30~17:00 2. 淡季(11月1日~3月31日):07:00~19:00 停止售票时间:17:00 园中园(含文昌院、德和园、佛香阁、苏州街澹宁堂):09:00~18:00",
          "attention": [
            {
              "name": "【门票优惠政策】",
              "description": "1. 身高1.2米以下儿童免票。 2. 北京市65岁以上老年人凭老年证免票;外地70周岁以上(含70周岁)老年人凭有效证件,门票半价优惠。 3. 大、中、小学学生(不含成人教育学生)、外国留学生凭学生证,门票半价优惠。 4. 残疾人、离休干部、离休军人、现役军人、武警官兵、省、部级以上劳模凭有效证件免票。 5. 持有社会保障金领取证的人员凭有效证件,门票半价优惠。"
            }
          ]
        }
      }
    }

    解析这个 Json 并且拿到以上 key 对应的 value 代码如下:

    先根据拿到的 Json 字符串中的 key 对象属性来定义 Model 类:

    public class Location
        {
            public double lng { get; set; }
            public double lat { get; set; }
        }
    
        public class Attention
        {
            public string name { get; set; }
            public string description { get; set; }
        }
    
        public class TicketInfo
        {
            public string price { get; set; }
            public string open_time { get; set; }
            public List<Attention> attention { get; set; }
        }
    
        public class Result
        {
            public string name { get; set; }
            public Location location { get; set; }
            public string telephone { get; set; }
            public string star { get; set; }
            public string url { get; set; }
            public string @abstract { get; set; }
            public string description { get; set; }
            public TicketInfo ticket_info { get; set; }
        }
    
        public class RootObject
        {
            public int error { get; set; }
            public string status { get; set; }
            public string date { get; set; }
            public Result result { get; set; }
        }

    获取所有的 key & value:

     var rs = JsonConvert.DeserializeObject<RootObject>(json);
  • 相关阅读:
    Hard Rock
    Codeforces Round #416 (Div. 2) B. Vladik and Complicated Book
    codeforces 793B. Igor and his way to work
    codeforces 1B Spreadsheets
    HDU 1069 Monkey and Banana
    codeforces 2B The least round way
    【机器学习】 通俗说拟合
    python-八皇后问题
    python-核心知识思维导图
    python-@property 属性
  • 原文地址:https://www.cnblogs.com/byvar/p/4795079.html
Copyright © 2011-2022 走看看