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方便了。