读取这样的
Morover在最后一个示例中,如果请求是坏的,那么可能有类似
JSON响应示例1:
{
"destination_addresses" : [ "Długa 50, 05-075 Warszawa, Slovakia" ],
"origin_addresses" : [ "Wilenska 2, Zabrze, Slovakia" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "324 km",
"value" : 323619
},
"duration" : {
"text" : "3 hours 16 mins",
"value" : 11776
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
在这种情况下,我应该计算为:324
JSON响应示例2:(可以有更多类似于此处的元素)
{
"destination_addresses" : [ "Długa 50, 05-075 Warszawa, Slovakia" ],
"origin_addresses" : [ "Wilenska 2, Zabrze, Slovakia" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "324 km",
"value" : 323619
},
"duration" : {
"text" : "3 hours 16 mins",
"value" : 11776
},
"status" : "OK"
},
{
"distance" : {
"text" : "192 km",
"value" : 191950
},
"duration" : {
"text" : "2 hours 26 mins",
"value" : 8732
},
"status" : "OK"
},
]
}
],
"status" : "OK"
}
在这种情况下,我应该计算为:516
JSON响应示例3:(某些状态与“OK”不同)
{
"destination_addresses" : [ "", "", "" ],
"origin_addresses" : [ "" ],
"rows" : [
{
"elements" : [
{
"status" : "NOT_FOUND"
},
{
"status" : "OK"
},
{
"status" : "NOT_FOUND"
}
]
}
],
"status" : "ERR"
}
在这种情况下,我应该得到异常
您可以使用https://json2csharp.com/根据您的json结构生成C#类。
然后安装nuget包https://www.nuget.org/packages/json.net/
然后可以尝试以下代码:
var sampleJson = @"{
""destination_addresses"" : [ ""Długa 50, 05-075 Warszawa, Slovakia"" ],
""origin_addresses"" : [ ""Wilenska 2, Zabrze, Slovakia"" ],
""rows"" : [
{
""elements"" : [
{
""distance"" : {
""text"" : ""324 km"",
""value"" : 323619
},
""duration"" : {
""text"" : ""3 hours 16 mins"",
""value"" : 11776
},
""status"" : ""OK""
},
{
""distance"" : {
""text"" : ""192 km"",
""value"" : 191950
},
""duration"" : {
""text"" : ""2 hours 26 mins"",
""value"" : 8732
},
""status"" : ""OK""
},
]
}
],
""status"" : ""OK""
}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(sampleJson);
if (obj.status != "OK")
{
throw new Exception($"Status is: {obj.status}");
}
if (obj.rows.Any(r => r.elements.Any(e => e.status != "OK")))
{
throw new Exception("some of the elements status is not ok");
}
var allDistanceText = obj.rows?.Select(e => e.elements).SelectMany(e => e.Select(d => d.distance?.text));
int sum = allDistanceText.Select(dt => dt?.Replace("km", "")?.Trim())
.Sum(dt =>
{
if (int.TryParse(dt, out int results))
{
return results;
}
return 0;
});
sum.Dump();