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

时间:2022-10-08 18:31:42

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. The following code fragment illustrates how my request is done.

我只对具有纬度和经度的位置对象感兴趣,并且想知道如何在c#中导航json对象树以从HttpContent中检索它们作为来自HttpClient上的GetAsync的响应。以下代码片段说明了我的请求是如何完成的。

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?

我怎么能读到位置对象?

2 个解决方案

#1


2  

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:

输出:

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

#2


2  

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. Once cast to dynamic I can then go ahead and access the object using familiar object syntax.

JSON字符串表示具有三个属性的对象,该属性被解析为JObject类并强制转换为动态。一旦转换为动态,我就可以继续使用熟悉的对象语法访问对象。

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

#1


2  

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:

输出:

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

#2


2  

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. Once cast to dynamic I can then go ahead and access the object using familiar object syntax.

JSON字符串表示具有三个属性的对象,该属性被解析为JObject类并强制转换为动态。一旦转换为动态,我就可以继续使用熟悉的对象语法访问对象。

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