解析Newtonsoft.Json的小例子

HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)(request.EndGetResponse(result));
stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, false);
string apiText = reader.ReadToEnd();
JObject jsonObj = null;
try
{
    jsonObj = JObject.Parse(apiText);
    if (jsonObj.Count == 1 || (int)(jsonObj["status"]) != 0) this.isError = true;
    else
    {
        string provinceName = (string)jsonObj["result"]["address_component"]["province"];
        string cityName = this.cityName_s = (string)jsonObj["result"]["address_component"]["city"];
        string districtName = (string)jsonObj["result"]["address_component"]["district"];
        string street = (string)jsonObj["result"]["address_component"]["street"];
/*下面是解析JArray的部分*/
        JArray jlist = JArray.Parse(jsonObj["result"]["pois"].ToString()); //将pois部分视为一个JObject,JArray解析这个JObject的字符串
        LocationItem locationitem = null;      //存储附近的某个地点的信息
        locations = new List<LocationItem>();  //附近位置的列表
        for(int i = 0; i < jlist.Count ; ++i)  //遍历JArray
        {
            locationitem = new LocationItem();
            JObject tempo = JObject.Parse(jlist[i].ToString());
            locationitem.id = tempo["id"].ToString();
            locationitem.title = tempo["title"].ToString();
            locationitem._distance = tempo["_distance"].ToString();
            locationitem.address = tempo["address"].ToString();
            locationitem.category = tempo["category"].ToString();
            locationitem.location.lat = tempo["location"]["lat"].ToString();
            locationitem.location.lng = tempo["location"]["lng"].ToString();
            locations.Add(locationitem);
        }
    }
}
catch (Exception)
{
    isError = true;
}

 

其中使用了两个类:

public class LngLat
    {
        public string lat { get; set; }
        public string lng { get; set; }
    }
    public class LocationItem
    {
        public string id{get;set;} //
        public string title { get; set; } //名称
        public string address { get; set; } //地址
        public string category { get; set; } //类型
        public LngLat location { get; set; } //经纬度
        public string _distance { get; set; } //距离(米)

        public LocationItem()
        {
            id = "0";
            title = "";
            address = "";
            _distance = "0";
            location = new LngLat { lng = "0", lat = "0" };
            category = "";
        }
    }

 

这样就完成了这个复杂json数据的解析。JSON数组访问还有用数组下标方式的,那个就需要数组至少要有足够的个数,如要取得上面那个json数据的 中国技术大厦A座 ,就是用jsonObj["result"]["pois"][1]["title"].ToString() ,即访问了result下pois数组的第2个节点的title信息,但是要遍历所有的数据就明显不如JArray方便了。    

转载于:https://my.oschina.net/robortly/blog/698598

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值