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

时间:2016-06-02 15:51:37

标签: c# json parsing httpclient

我试图从google maps api解析json以进行地理编码。

JSON是:

wix:Component[contains(concat(wix:File/@Source, ,','), '.cs,')]

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

location

我如何阅读位置对象?

3 个答案:

答案 0 :(得分:2)

一种选择是将JSON反序列化为类型化类,其他使用动态类型。

Using JSON.NET for dynamic JSON parsing

  

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)

这是我通常的做法。 (我将你的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);
}

输出:

enter image description here

答案 2 :(得分:0)

作为一种选择,可以使用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
        };
}