解析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 这样就完成了这个复杂json数据的解析。JSON数组访问还有用数组下标方式的,那个就需要数组至少要有足够的个数,如要取得上面那个json数据的 中国技术大厦A座 ,就是用jsonObj["result"]["pois"][1]["title"].ToString(),即访问了result下pois数组的第2个节点的title信息,但是要遍历所有的数据就明显不如JArray方便了。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |