gpt4 book ai didi

C# - response.Content.ReadAsAsync 没有像我认为的那样工作

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

我正在开发一个 winform 应用程序,并且正在对 GoogleMaps API 进行 API 调用。但由于某种原因,我无法得到回应。或者实际上,我确实收到了回复,但无法对其执行任何操作。

我的代码:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GoogleMaps
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();

setup().Wait();
}

static HttpClient client = new HttpClient();

static async Task setup()
{
client.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/geocode/json");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

}

static async Task<Result> getAdress(int huisnummer, string postcode)
{
Result address = null;
HttpResponseMessage response = await client.GetAsync($"?address=00+1234AB&key=MYKEY");
if (response.IsSuccessStatusCode)
{
address = await response.Content.ReadAsAsync<Result>();
}
return address;
}

private async void BTN_submit_Click(object sender, EventArgs e)
{
Result address = new Result();

address = await getAdress(31, "8256SC");

richTextBox1.Text = "address is:" + address.formatted_address;
}
}
}

还有我的“将 JSON 作为类粘贴”类:

namespace GoogleMaps
{

public class Rootobject
{
public Result[] results { get; set; }
public string status { get; set; }
}

public class Result
{
public Address_Components[] address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public string place_id { get; set; }
public string[] types { get; set; }
}

public class Geometry
{
public Location location { get; set; }
public string location_type { get; set; }
public Viewport viewport { get; set; }
}

public class Location
{
public float lat { get; set; }
public float lng { get; set; }
}

public class Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}

public class Northeast
{
public float lat { get; set; }
public float lng { get; set; }
}

public class Southwest
{
public float lat { get; set; }
public float lng { get; set; }
}

public class Address_Components
{
public string long_name { get; set; }
public string short_name { get; set; }
public string[] types { get; set; }
}

}

我现在的输出什么都没有。但我确实得到了 200 的回应。我该如何解决这个问题?

最佳答案

您正在反序列化到错误的类中。正确的类是 Rootobject

address = await response.Content.ReadAsAsync<Rootobject>();

而不是使用Result

address = await response.Content.ReadAsAsync<Result>();

示例地理编码 API 响应 ( from Google API Docs ):

{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
}]
...
}],
"status" : "OK"
}

关于C# - response.Content.ReadAsAsync<Result> 没有像我认为的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43699956/

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