Using Json.NET to parse result returned by Google Maps API

偶尔善良 提交于 2019-12-25 03:58:09

问题


I am trying to use google map api's web service to make a web request, and get the json string, and then get the latitude and longitude I need for the input address.

Everything is fine. I got the json string I need.

Now I am using Json.net to parse the string.

I don't know why, but I simply cannot convert it into a JArray.

Here is the json string

Can anyone teach me how to write the c# code to get the lat and lng in geometry > location?

Thanks

Here is my codes and the bug screenshot


回答1:


You have a few options when using JSON.NET to Parse the JSON.

The best option, IMHO, is to use Serialization to pull the object back into a structured type that you can manipulate as you could any other class. For this you can see serialization in the JSON.NET documentation (I can also post more details if that isn't clear enough).

If all you want is to grab the address, as you listed in your question, you can also use the LINQ feature to pull that information back. You could use code similar to the following to pull it off (the key lies in the SelectToken method to pull back the details you need).

    Dim json As Newtonsoft.Json.Linq.JObject
    json = Newtonsoft.Json.Linq.JObject.Parse(jsonString)
    json.SelectToken("results.formatted_address").ToString()

You can also use all the normal power of Linq to traverse the JSON as you'd expect. See the LINQ documentation as well.




回答2:


[I realize this is an old question, but in the off chance it helps someone else...]

The problem here is that json["results"] is a JArray, but you are not querying it like one. You need to use an array index to get the first (and only, in this case) element, then you can access the objects inside it.

string address = json["results"][0]["formatted_address"].Value<string>();

To get the latitude and longitude you can do:

JToken location = json["results"][0]["geometry"]["location"];
double lat = location["lat"].Value<double>();
double lng = location["lng"].Value<double>();


来源:https://stackoverflow.com/questions/7515679/using-json-net-to-parse-result-returned-by-google-maps-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!