C#解析JSON数据

本篇文章主要介绍C#对Json数据的读取。

主要操作过程是:

 

  1. 发送Http请求获取Json数据
  2. 把获取的Json数据转换成C#中的类

 

 

下面我们以12306火车票余票的数据为例进行切入。

首先来看一下http请求和获取到Json数据的格式: 

Http RequestGET https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2016-04-01&leftTicketDTO.from_station=BJP&leftTicketDTO.to_station=SHH&purpose_codes=ADULT HTTP/1.1

Host: kyfw.12306.cn

Connection: keep-alive
Cache-Control: no-cache
Accept: */*
X-Requested-With: XMLHttpRequest
If-Modified-Since: 0
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Referer: https://kyfw.12306.cn/otn/leftTicket/init
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8

 服务器端返回的余票信息:

{

  "validateMessagesShowId": "_validatorMessage",
  "status": true,
  "httpstatus": 200,
  "data": [
    {
      "queryLeftNewDTO": {
        "train_no": "240000G1010B",
        "station_train_code": "G101",
        "start_station_telecode": "VNP",
        "start_station_name": "北京南",
        "end_station_telecode": "AOH",
        "end_station_name": "上海虹桥",
        "from_station_telecode": "VNP",
        "from_station_name": "北京南",
        "to_station_telecode": "AOH",
        "to_station_name": "上海虹桥",
        "start_time": "07:00",
        "arrive_time": "12:37",
        "day_difference": "0",
        "train_class_name": "",
        "lishi": "05:37",
        "canWebBuy": "Y",
        "lishiValue": "337",
        "yp_info": "O055300106M0933000689174800011",
        "control_train_day": "20301231",
        "start_train_date": "20160401",
        "seat_feature": "O3M393",
        "yp_ex": "O0M090",
        "train_seat_feature": "3",
        "seat_types": "OM9",
        "location_code": "P2",
        "from_station_no": "01",
        "to_station_no": "10",
        "control_day": 59,
        "sale_time": "1230",
        "is_support_card": "1",
        "controlled_train_flag": "0",
        "controlled_train_message": "正常车次,不受控",
        "gg_num": "--",
        "gr_num": "--",
        "qt_num": "--",
        "rw_num": "--",
        "rz_num": "--",
        "tz_num": "--",
        "wz_num": "--",
        "yb_num": "--",
        "yw_num": "--",
        "yz_num": "--",
        "ze_num": "有",
        "zy_num": "有",
        "swz_num": "11"
      },
      "secretStr": "MjAxNi0wNC0wMSMwMCNHMTAxIzA1OjM3IzA3OjAwIzI0MDAwMEcxMDEwQiNWTlAjQU9IIzEyOjM3I%2BWMl%2BS6rOWNlyPkuIrmtbfombnmoaUjMDEjMTAjTzA1NTMwMDEwNk0wOTMzMDAwNjg5MTc0ODAwMDExI1AyIzE0NTkwNjc3NDQzOTUjMTQ1NDM4NzQwMDAwMCMzMDFGQTJDNzg1OTI4OTlGNjEzRDg2NEQwRkMwNzlFMzFBQTFCQ0Q1RjNDNTgyNENGMjVCOTQ2QQ%3D%3D",
      "buttonTextInfo": "预订"
    },
    ...
    "messages": [ ],
    "validateMessages": { }
}

 

添加引用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 引用Json序列化命名空间之前需要在项目引用之中添加System.Runtime.Serialization的引用
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ComponentModel;
using System.Net;

 

定义Class:

[DataContract]
public class LeftTicketQueryResult
{
    [DataMember]
    public List<LeftTicketsInfo> data { get; set; }

    [DataMember]
    public string httpstatus { get; set; }

    [DataMember]
    public string status { get; set; }
}

[DataContract]
public class LeftTicketsInfo
{
    [DataMember]
    public string buttonTextInfo { get; set; }

    [DataMember]
    public LeftTicketDetails queryLeftNewDTO {get;set;}
}

[DataContract]
public class LeftTicketDetails
{
    [DataMember]
    public string arrive_time { get; set; }

    [DataMember]
    public string start_time { get; set; }

    [DataMember]
    public string to_station_name { get; set; }

    [DataMember]
    public string from_station_name { get; set; }

    [DataMember]
    public string lishi { get; set; }

    [DataMember]
    public string station_train_code { get; set; }

    [DataMember]
    public string start_train_date { get; set; }

    [DataMember]
    public string day_difference { get; set; }

    [DataMember]
    public string gg_num { get; set; }

    [DataMember]
    public string gr_num { get; set; }

    [DataMember]
    public string qt_num { get; set; }

    [DataMember]
    public string rw_num { get; set; }

    [DataMember]
    public string rz_num { get; set; }

    [DataMember]
    public string swz_num { get; set; }

    [DataMember]
    public string tz_num { get; set; }

    [DataMember]
    public string wz_num { get; set; }

    [DataMember]
    public string yb_num { get; set; }

    [DataMember]
    public string yw_num { get; set; }

    [DataMember]
    public string yz_num { get; set; }

    [DataMember]
    public string ze_num { get; set; }

    [DataMember]
    public string zy_num { get; set; }
}
类定义

 

执行代码:

namespace ParseJson
{

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                /// Turn off SSL certificate validation
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });

                HttpWebRequest request = WebRequest.CreateHttp("https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2016-04-01&leftTicketDTO.from_station=BJP&leftTicketDTO.to_station=SHH&purpose_codes=ADULT");
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(LeftTicketQueryResult));
                LeftTicketQueryResult leftTicketResult = (LeftTicketQueryResult)jsonSerializer.ReadObject(response.GetResponseStream());

                Console.WriteLine("Press any key to exit...");
                Console.Read();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.Read();
            }
        }
    }
}

结果:

 

 

然后我们就可以像操作类的属性一样对获取的JSON数据进行访问了。 

 

posted @ 2016-03-27 21:29  silverbullet11  阅读(3762)  评论(0编辑  收藏  举报