如何解析Google Distance Matrix API中的JSON输出?

时间:2011-06-19 11:07:30

标签: asp.net-mvc-3 google-api

http://www.giantflyingsaucer.com/blog/?p=2227&cpage=1提供了一种很好的ASP.NET MVC和Google API集成方法。

在URL缩短的情况下,响应结构很简单:

private class GoogleShortenedURLResponse
{
    public string id { get; set; }
    public string kind { get; set; }
    public string longUrl { get; set; }
}

我对Google Distance Matrix API采用了相同的方法......但我不知道如何定义响应结构......你有什么想法吗?

1 个答案:

答案 0 :(得分:6)

以下内容适合该法案:

using System;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

public class DistanceResponse
{
    public string Status { get; set; }
    public string[] Origin_Addresses { get; set; }
    public string[] Destination_Addresses { get; set; }
    public Row[] Rows { get; set; }
}

public class Row
{
    public Element[] Elements { get; set; }
}

public class Element
{
    public string Status { get; set; }
    public Item Duration { get; set; }
    public Item Distance { get; set; }
}

public class Item
{
    public int Value { get; set; }
    public string Text { get; set; }
}

class Program
{
    static void Main()
    {
        using (var client = new WebClient())
        {
            var values = HttpUtility.ParseQueryString(string.Empty);
            values["origins"] = "Vancouver BC|Seattle";
            values["destinations"] = "San Francisco|Victoria BC";
            values["mode"] = "bicycling";
            values["language"] = "fr-FR";
            values["sensor"] = "false";
            var uriBuilder = new UriBuilder("http://maps.googleapis.com/maps/api/distancematrix/json");
            uriBuilder.Query = values.ToString();
            var result = client.DownloadData(uriBuilder.ToString());
            var json = Encoding.UTF8.GetString(result);

            var serializer = new JavaScriptSerializer();
            var distanceResponse = serializer.Deserialize<DistanceResponse>(json);
            if (string.Equals("ok", distanceResponse.Status, StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("origin addresses: {0}", string.Join(", ", distanceResponse.Origin_Addresses));
                Console.WriteLine("destination addresses: {0}", string.Join(", ", distanceResponse.Destination_Addresses));
                foreach (var row in distanceResponse.Rows)
                {
                    foreach (var element in row.Elements)
                    {
                        if (string.Equals("ok", element.Status, StringComparison.OrdinalIgnoreCase))
                        {
                            Console.WriteLine("Distance: {0} {1}", element.Distance.Text, element.Distance.Value);
                            Console.WriteLine("Duration: {0} {1}", element.Duration.Text, element.Duration.Value);
                        }
                    }
                }
            }
        }
    }
}