rAJ
rAJ

Reputation: 1433

foreach loop to fetch JSON value

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.

Upvotes: 2

Views: 1944

Answers (1)

dbc
dbc

Reputation: 116795

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");
        }

Upvotes: 2

Related Questions