简体   繁体   English

C#使用HttpClient从JSON响应中获取特定对象

[英]C# Get specific object from JSON response using HttpClient

I'm trying to parse json from the google maps api for geocoding. 我正在尝试从google maps api解析json以进行地理编码。

The JSON is: JSON是:

{
"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. 我只对具有纬度和经度的location对象感兴趣,并且想知道如何在c#中导航json对象树以从HttpContent中检索它们作为来自HttpClient上的GetAsync的响应。 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? 我怎么能读到位置对象?

One option would be to deserialize JSON to typed classes and other use dynamic types. 一种选择是将JSON反序列化为类型化类和其他使用动态类型。

Using JSON.NET for dynamic JSON parsing 使用JSON.NET进行动态JSON解析

The JSON string represents an object with three properties which is parsed into a JObject class and cast to dynamic. JSON字符串表示具有三个属性的对象,该属性被解析为JObject类并强制转换为动态。 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");            
}

Here's how I usually do it. 这是我通常这样做的方式。 (I saved your json object into D:/json.txt) (我将你的json对象保存到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: 输出:

在此输入图像描述

As an option, to retrieve coordinates you could use strongly typed object provided by Geocoding package: 作为选项,要检索坐标,您可以使用Geocoding包提供的强类型对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM