【发布时间】:2019-02-21 22:38:34
【问题描述】:
在调用 Google Geolocation API 时,结果 (json) 会像这样返回
示例(抱歉,我无法正确格式化 Json)
{"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "EiQ3LCA3IExha2VzaWRlIERyLCBSeWUsIE5ZIDEwNTgwLCBVU0EiHRobChYKFAoSCQH00P0vl8KJEQ2d7mWAl0jrEgE3",
"types" : [ "subpremise" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJ1YqpR4eRwokRTuazxMrnKiM",
"types" : [ "establishment", "point_of_interest" ]
} ],
"routes" : [{
"bounds" : {
"northeast" : {
"lat" : 41.0044903,
"lng" : -73.6892836
},
"southwest" : {
"lat" : 40.9575099,
"lng" : -73.7589093
}
},
"copyrights" : "Map data ©2018 Google",
"legs" : [
{
"distance" : {
"text" : "7.0 mi",
"value" : 11325
},
"duration" : {
"text" : "15 mins",
"value" : 889
},
"end_address" : "851 Fenimore Rd, Mamaroneck, NY 10543, USA",
"end_location" : {
"lat" : 40.9575099,
"lng" : -73.75338219999999
},
"start_address" : "7 Pheasant Run #7, Rye, NY 10580, USA",
"start_location" : {
"lat" : 40.99850199999999,
"lng" : -73.689633
},
我需要从返回的数据中检索各种单个项目,例如,持续时间:文本值。 有没有办法过滤掉 API 调用中的多余部分,或者我如何从 Json 中解析它?
我尝试反序列化为一个对象,然后对其进行迭代并获取腿数组,但是 A. 这不起作用,因为该对象位于大项目上,而不是集合上,而 B. 这似乎很浪费。
public int TravelTimeInMinutes(string origin, string destination, string apiKey)
{
var timeToTravel = 0;
var url = DirectionsUrlBase + ConvertOriginFormat(origin) + ConvertDestinationFormat(destination) + "&key="+ apiKey;
var client = new HttpClient();
// Add the Accept type header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// get the response
// make method async once working
var response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var result = JsonConvert.SerializeObject(response.Content.ReadAsStringAsync().Result());
dynamic array = JsonConvert.DeserializeObject(result);
foreach (var item in array)
{
}
//… rest removed for brevity
如何深入检索单个值?我认为我的错误在于我如何反序列化响应。我还有一个带有 Text 和 Value 属性的 Duration 类。如果可能的话,我想反序列化到那个类。
跟进
我在序列化调用之后添加了.Result
response.Content.ReadAsStringAsync().Result()
现在返回正确的 json
现在我怎样才能从中解析单个值,或者我可以反序列化到 Duration 类中。 根据查尔斯的建议
我有一个根对象
公共类 MapsDirectionObject { 公共 GeocodedWaypoints[] geocoded_waypoints { 获取;放; } 公共路线[]路线{获取;放; } }
public class Routes
{
public object[] Value { get; set; }
}
public class GeocodedWaypoints
{
public string geocoder_status { get; set; }
public string place_id { get; set; }
public string[] types { get; set; }
}
由于返回的 json 只有两个主要的子类,路线和航路点,所以我也有这些类。带有以下错误的反序列化错误。
Newtonsoft.Json.JsonSerializationException: '错误转换值 "{ "geocoded_waypoints" : [ {
如果我删除序列化的 .Result 调用,我可以映射到该对象,但值为 null。
【问题讨论】: