asp.net mvc 3-如何在Google Distance Matrix API中解析JSON输出



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

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

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

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

以下内容应符合要求:

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);
                        }
                    }
                }
            }
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新