解析Newtonsoft.Json的小例子

前端之家收集整理的这篇文章主要介绍了解析Newtonsoft.Json的小例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. HttpWebRequest request = (HttpWebRequest)result.AsyncState;
  2. HttpWebResponse response = (HttpWebResponse)(request.EndGetResponse(result));
  3. stream = response.GetResponseStream();
  4. StreamReader reader = new StreamReader(stream,false);
  5. string apiText = reader.ReadToEnd();
  6. JObject jsonObj = null;
  7. try
  8. {
  9. jsonObj = JObject.Parse(apiText);
  10. if (jsonObj.Count == 1 || (int)(jsonObj["status"]) != 0) this.isError = true;
  11. else
  12. {
  13. string provinceName = (string)jsonObj["result"]["address_component"]["province"];
  14. string cityName = this.cityName_s = (string)jsonObj["result"]["address_component"]["city"];
  15. string districtName = (string)jsonObj["result"]["address_component"]["district"];
  16. string street = (string)jsonObj["result"]["address_component"]["street"];
  1. /*下面是解析JArray的部分*/
  2. JArray jlist = JArray.Parse(jsonObj["result"]["pois"].ToString()); //将pois部分视为一个JObject,JArray解析这个JObject的字符串
  3. LocationItem locationitem = null; //存储附近的某个地点的信息
  4. locations = new List<LocationItem>(); //附近位置的列表
  5. for(int i = 0; i < jlist.Count ; ++i) //遍历JArray
  6. {
  7. locationitem = new LocationItem();
  8. JObject tempo = JObject.Parse(jlist[i].ToString());
  9. locationitem.id = tempo["id"].ToString();
  10. locationitem.title = tempo["title"].ToString();
  11. locationitem._distance = tempo["_distance"].ToString();
  12. locationitem.address = tempo["address"].ToString();
  13. locationitem.category = tempo["category"].ToString();
  14. locationitem.location.lat = tempo["location"]["lat"].ToString();
  15. locationitem.location.lng = tempo["location"]["lng"].ToString();
  16. locations.Add(locationitem);
  17. }
  18. }
  19. }
  20. catch (Exception)
  21. {
  22. isError = true;
  23. }

其中使用了两个类:

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

猜你在找的Json相关文章