现在的位置: 首页 > 综合 > 正文

解析json数据(初用json.Net)

2013年09月13日 ⁄ 综合 ⁄ 共 1347字 ⁄ 字号 评论关闭

      要解析类似以下如此数据:

{"weatherinfo":{"city":"长安","cityid":"101110102","temp":"7","WD":"西风","WS":"1级","SD":"50%","WSE":"1","time":"18:40","isRadar":"0","Radar":""}}

创建了那么两个类供解析后存放数据用。

class WhetherInfo
        {
            public string  city { get; set; }
            public string temp { get; set; }
            public string cityid { get; set; }
            public string WD { get; set; }
            public string WS { get; set; }
            public string SD { get; set; }
            public string WSE { get; set; }
            public string time { get; set; }
            public string isRader { get; set; }
            public string Rader { get; set; }
        }

        class Info
        {
            public WhetherInfo weatherinfo { get; set; }
        }

一开始考虑用DataContractJsonSerializer类,但是使用时候报securityException错误。。研究半天,无果。好像是这个类不支持解析如此复杂的json。

后来发现有个叫json.NET这个库。JSON.NET官网

里面有个叫LINQ TO JSON。貌似支持解析如此数据。



首先添加下载下来的的Newtonsoft.Json.dll添加进来。

添加代码:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

依然解析以让数据。

JObject json = JObject.Parse(e.Result);
            Info info = new Info
            {
                weatherinfo = new WhetherInfo {//

//由上面需要解析的数据可知,我们需要的数据在在weatherinfo这个节点的下一个节点

                    city = (string)json["weatherinfo"]["city"],
                    cityid = (string)json["weatherinfo"]["cityid"],
                    isRader = (string)json["weatherinfo"]["isRader"],
                    Rader = (string)json["weatherinfo"]["Rader"],
                    SD = (string)json["weatherinfo"]["SD"],
                    temp = (string)json["weatherinfo"]["temp"],
                    time = (string)json["weatherinfo"]["time"],
                    WD = (string)json["weatherinfo"]["WD"],
                    WS = (string)json["weatherinfo"]["WS"],
                    WSE = (string)json["weatherinfo"]["WSE"]
                }
            };
            MessageBox.Show(info.weatherinfo.city);

成功!

不过要把解析出来的对象一个一个赋值还真是麻烦。。。


抱歉!评论已关闭.