NicolasL
NicolasL

Reputation: 119

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 ...
      }
}

How might I read the location object?

Upvotes: 4

Views: 4007

Answers (3)

Dmitry Pavlov
Dmitry Pavlov

Reputation: 28310

As an option, to retrieve coordinates you could use strongly typed object provided by Geocoding package:

public async Task<Coordinates> GeoCode(string address) 
{
    GoogleGeocoder geocoder = new GoogleGeocoder();
    IEnumerable<GoogleAddress> addresses = await geocoder.GeocodeAsync(address);    

    GoogleAddress first = addresses?.FirstOrDefault();

    return first == null
        ? null
        : new Coordinates
        {
            Latitude = first.Coordinates.Latitude,
            Longitude = first.Coordinates.Longitude
        };
}

Upvotes: 0

Veverke
Veverke

Reputation: 11378

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

Upvotes: 3

Edgars Pivovarenoks
Edgars Pivovarenoks

Reputation: 1684

One option would be to deserialize JSON to typed classes and other use dynamic types.

Using JSON.NET for dynamic JSON parsing

The JSON string represents an object with three properties which is parsed into a JObject class and cast to dynamic. Once cast to dynamic I can then go ahead and access the object using familiar object syntax.

public void JValueParsingTest()
{
    var jsonString = @"{""Name"":""Rick"",""Company"":""West Wind"",
                        ""Entered"":""2012-03-16T00:03:33.245-10:00""}";

    dynamic json = JValue.Parse(jsonString);

    // values require casting
    string name = json.Name;
    string company = json.Company;
    DateTime entered = json.Entered;

    Assert.AreEqual(name, "Rick");
    Assert.AreEqual(company, "West Wind");            
}

Upvotes: 2

Related Questions