所以看起来对 Google Maps API 的查询会返回一个 JSON 对象 (SRC:https://stackoverflow.com/a/34597393/8502032)。 C# 本身不处理 JSON,因此您可以使用 Newtonsoft 的 Json.NET 库来帮助您将对象解析为更可行的内容。
您可以通过多种方式从那里访问信息。一种是使用 Json.net 的反序列化功能。这将获取 JSON 字符串并将其插入到可用对象中。您可以创建一个自定义对象,该对象将抓取您关心的 JSON 部分,然后删除其余部分。
这来自我链接的答案,我们将使用它作为我们尝试访问的数据集。
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 34.1330949,
"lng" : -117.9143879
},
"southwest" : {
"lat" : 33.8068768,
"lng" : -118.3527671
}
},
"copyrights" : "Map data ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "35.9 mi",
"value" : 57824
},
"duration" : {
"text" : "51 mins",
"value" : 3062
},
"end_address" : "Universal Studios Blvd, Los Angeles, CA 90068, USA",
"end_location" : {
"lat" : 34.1330949,
"lng" : -118.3524442
},
"start_address" : "Disneyland (Harbor Blvd.), S Harbor Blvd, Anaheim, CA 92802, USA",
"start_location" : {
"lat" : 33.8098177,
"lng" : -117.9154353
},
... Additional results truncated in this example[] ...
因此,为了访问我们想要的内容,我们将创建一系列与我们想要的信息相匹配的类。
class Routes
{
Legs legs;
}
class Legs
{
EndLocation endLocation;
}
class EndLocation
{
string lat;
string lon;
}
这是粗略的代码,我无法对其进行测试,但希望它能给你一个好的开始方向。
using Newtonsoft.Json;
void ReadJson()
{
// Let's say for now that our results are held in a file, for simplicity's sake
string jsonString = File.ReadAllText(location.txt);
// Now we'll call the deserializer, since we have the JSON string.
// It'll turn it into our object automatically with the template.
Routes locationInfo = JsonConvert.DeserializeObject<Routes>(jsonString);
serializer.Deserialize(jsonString, locationInfo);
}
之后,您应该能够访问 locationInfo 对象,就像您访问任何常规 C# 对象一样。
这应该工作,但至少我希望能给你一个很好的方向来解决你的问题。