2

I am trying to fetch all the latitude and longitude of my JSON result.

JSON Result (have many records):

"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"
  },

for particular record (say record first):

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"];

for fetching all records:

foreach(var item in jarr)
{
double lt = Convert.ToDouble(item[jarr["geometry"]["location"]["lat"]]);
}

For fetching one record it works fine but for all records its not working.

2
  • Change your line to be double lt = Convert.ToDouble(jarr[item]["geometry"]["location"]["lat"]);. Commented Jul 1, 2015 at 21:44
  • Convert.ToDouble() assumes the input string is in the current thread culture. You should probably use a culture-invariant method such as the JToken explicit cast. Commented Jul 1, 2015 at 22:10

1 Answer 1

2

You can use SelectTokens to pick out the fields of interest from your JSON. Since this method supports JSONPath query syntax you can use the "*" wildcard to loop through all entries in the "results" array:

        var locations = JToken.Parse(googleResult)
            .SelectTokens("results[*].geometry.location")
            .Select(t => new { Lat = (double)t["lat"], Lng = (double)t["lng"] })
            .ToList();

Or, if you prefer a foreach loop:

        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");
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.