gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:43:53 25 4
gpt4 key购买 nike

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 采用了相同的方法...但我不知道如何定义响应结构...您知道吗?

最佳答案

以下应该符合要求:

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

关于asp.net-mvc-3 - 如何解析 Google Distance Matrix API 中的 JSON 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6402001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com