反序列化Google方向JSON

时间:2016-06-16 08:15:10

标签: c# asp.net json google-maps json-deserialization

首次使用JSON及相关内容时,我正在尝试从此请求中获取所有可能路由的距离/持续时间:https://maps.googleapis.com/maps/api/directions/json?origin=41.2091585,-8.5763016&destination=41.258913,-8.636942&mode=driving&alternatives=true&avoid=tolls&language=pt-PT&key=AIzaSyDuhdvLAny3MpraXKX-bahkXZJolm7KLbE

我使用“将JSON粘贴为类”获得以下类,并为以下每个类创建一个类:

public class Rootobject
    {
        public Geocoded_Waypoints[] geocoded_waypoints { get; set; }
        public Route[] routes { get; set; }
        public string status { get; set; }
    }

public class Route
    {
        public Bounds bounds { get; set; }
        public string copyrights { get; set; }
        public Leg[] legs { get; set; }
        public Overview_Polyline overview_polyline { get; set; }
        public string summary { get; set; }
        public object[] warnings { get; set; }
        public object[] waypoint_order { get; set; }
    }

public class Leg
    {
        public Distance distance { get; set; }
        public Duration duration { get; set; }
        public string end_address { get; set; }
        public End_Location end_location { get; set; }
        public string start_address { get; set; }
        public Start_Location start_location { get; set; }
        public Step[] steps { get; set; }
        public object[] traffic_speed_entry { get; set; }
        public Via_Waypoint[] via_waypoint { get; set; }
    }

public class Distance
    {
        public string text { get; set; }
        public int value { get; set; }
    }

public class Duration
{
    public string text { get; set; }
    public int value { get; set; }
}

对于上面提到的查询,我有3条不同的路线(又名“腿”),我想获得每条路线的距离/持续时间。
我想出了以下但是没有用。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();

    if (!string.IsNullOrEmpty(result))
    {
        Distance t = JsonConvert.DeserializeObject<Distance>(result);
        string distance1_Value = t.value;
        string distance1_Text = t.text;

        Duration d = JsonConvert.DeserializeObject<Duration>(result);
        string duration1_Value = d.value;
        string duration1_Value = d.text;
    }
}

任何帮助?
PS:如果有人能告诉我如何迭代抛出每个“腿”,这将是伟大的。

编辑:忘记提及我正在使用Newtonsoft。

1 个答案:

答案 0 :(得分:1)

我几天前找到了解决方案......

首先,我对你做了同样的事,但仍然没有为我工作,所以我深入了解这个工具自动生成的类,并注意到某些类在名称末尾缺少's' .. 步骤,正确的名称'步骤' 腿。正确的名字'腿' 路线。正确的名称'路线'

您是否必须在整个文档中修复此问题。 在此之后,您可以直接转换...

看看正确答案:[1]:http://pastie.org/10935748#9