gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:21:28 24 4
gpt4 key购买 nike

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

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

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

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

我如何读取位置对象?

最佳答案

这是我通常的做法。 (我把你的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

关于C# 使用 HttpClient 从 JSON 响应中获取特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com