NicolasL NicolasL - 6 months ago 138
JSON Question

C# Get specific object from JSON response using HttpClient

I'm trying to parse json from the google maps api for geocoding.

The JSON is:

{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224277,
"lng" : -122.0843288
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4237766802915,
"lng" : -122.0829798197085
},
"southwest" : {
"lat" : 37.4210787197085,
"lng" : -122.0856777802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}


I'm only interested in the
location
object with the latitude and longitude and would like to know how to navigate the json object tree within c# to retrieve them from a HttpContent as response from a GetAsync on a HttpClient.
The following code fragment illustrates how my request is done.

public async Task<Coordinates> GeoCode(string address)
{
HttpClient client= new HttpClient();
var baseUrl = "http://maps.google.com/maps/api/geocode/json?address=";
var addressEncoded = WebUtility.UrlEncode(address);
var response= await client.GetAsync(baseUrl + addressEncoded);

if(response.IsSuccessStatusCode)
{
//read location ...
}
}

Answer

Here's how I usually do it. (I saved your json object into D:/json.txt)

 var json = File.ReadAllText("D:/json.txt");
 var results = JObject.Parse(json).SelectToken("results") as JArray;

foreach (var result in results)
{
    var geometryEntry = result.SelectToken("geometry.location");
    var longitude = geometryEntry.Value<double>("lat");
    var latitude = geometryEntry.Value<double>("lng");

    Console.WriteLine("{0}, {1}", longitude, latitude);
}

Output:

enter image description here