我正在尝试获取JSON结果的所有纬度和经度。
JSON结果(有很多记录):
"results" : [
{
"geometry" : {
"location" : {
"lat" : 28.637255,
"lng" : 77.05202800000001
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "aef56d078ec3fcab6f4a966bd944d3d59973bd72",
"name" : "Homeopati Kendra",
"opening_hours" : {
"open_now" : false,
"weekday_text" : []
},
"place_id" : "ChIJQavdFRwFDTkRMRAhjCbIOnI",
"reference" : "CnRjAAAAwCoBEGDvsL4KeQNPyT2OsVF82b7FChIpUHRFQvGg8b1eR7FCv9I1nUPn0lFf50OVG9ug1PevkcZG813Lq9AAe1dK5GCgn99ajpQ1it9lafCwX3SaUwtiinLiepgptdHNz3NgDzhpVIx70a2D1KZcchIQvD4OS73_Jmr2wYQg4jtRjxoUjCnGT2M4XzDIXadJOtgA-LgRNR4",
"scope" : "GOOGLE",
"types" : [ "hospital", "health", "establishment" ],
"vicinity" : "C-29 , Vikas Nagar,Uttam Nagar, Vikas Nagar Extn, Hastsal, New Delhi"
},
特定记录(首先记录):
JObject obj = JObject.Parse(googleResult);
JArray jarr = (JArray)obj["results"];
double lt = (double)jarr[0]["geometry"]["location"]["lat"];
double lg = (double)jarr[0]["geometry"]["location"]["lng"];
用于获取所有记录:
foreach(var item in jarr)
{
double lt = Convert.ToDouble(item[jarr["geometry"]["location"]["lat"]]);
}
对于获取一条记录,它可以正常工作,但对于所有记录都不起作用。
答案 0 :(得分:1)
您可以使用SelectTokens
从您的JSON中挑选感兴趣的字段。由于此方法支持JSONPath query syntax,因此您可以使用"*"
通配符循环遍历"results"
数组中的所有条目:
var locations = JToken.Parse(googleResult)
.SelectTokens("results[*].geometry.location")
.Select(t => new { Lat = (double)t["lat"], Lng = (double)t["lng"] })
.ToList();
或者,如果您更喜欢foreach
循环:
JObject obj = JObject.Parse(googleResult);
JArray jarr = (JArray)obj["results"];
foreach (var item in jarr)
{
double lt = (double)item.SelectToken("geometry.location.lat");
double lg = (double)item.SelectToken("geometry.location.lng");
}