c# - ASP.NET 中的 Json 解析
问题描述
我想在 ASP.NET 中解析下面的 JSON。
{
"destination_addresses": [
"Address 1"
],
"origin_addresses": [
"Address 2"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "15.7 km",
"value": 15664
},
"duration": {
"text": "17 mins",
"value": 1036
},
"status": "OK"
}
]
}
],
"status": "OK"
}
我想从距离标记中检索文本和值。我能够到达直到元素。
var objectjson = JObject.Parse(response.Content);
dynamic dynJson = JsonConvert.DeserializeObject(objectjson["rows"].ToString());
var elements = dynJson[0].ToString();
var firstElement = JObject.Parse(elements);
如何进一步解析 json 以达到距离标记,然后是文本和值?
解决方案
创建一个类,如:
public class Distance {
public string text { get; set; }
public int value { get; set; }
}
public class Duration {
public string text { get; set; }
public int value { get; set; }
}
public class Element {
public Distance distance { get; set; }
public Duration duration { get; set; }
public string status { get; set; }
}
public class Row {
public List<Element> elements { get; set; }
}
public class Root {
public List<string> destination_addresses { get; set; }
public List<string> origin_addresses { get; set; }
public List<Row> rows { get; set; }
public string status { get; set; }
}
然后,您可以对其进行转换并轻松构建逻辑
var myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
站点参考: