C#-response.Content.ReadAsAsync<;结果>;不是我认为应该起作用的

C#-response.Content.ReadAsAsync<;结果>;不是我认为应该起作用的,c#,.net,C#,.net,我正在开发一个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

我正在开发一个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;
        }
    }
}

我现在的输出什么都没有。但我确实收到了200条回复。如何修复此问题?

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

address = await response.Content.ReadAsAsync<Rootobject>();
地理编码API响应()示例:


我现在的输出什么都没有。你这是什么意思?它是空实例吗?或者什么?使用像Fiddler这样的工具查看Google服务器返回的响应数据。服务器是否真的返回了您要查找的信息?我的输出是“address is:”可能您映射到了错误的类。结构似乎必须以根对象开始。address=wait response.Content.ReadAsAsync();是的,它确实返回了我正在寻找的东西。在浏览器中查看。是的,好的,我已经尝试过了,但是现在如何获得
格式化的\u地址
?我尝试将其添加到rootobject,但没有成功。我可以检索
格式化的\u地址
。这是在正确的地方,在你原来的类张贴在问题。没有必要将它移动到RootObject,但如果我只是尝试对我来说合适的东西,就会不断地出错。当我只将
result
更改为
Rootobject
时,我得到一个转换错误。如果我将它们全部更改为
Rootobject
它找不到
格式化的\u地址
@LuukWuijster,我只需对您的代码进行一次更改,我在回答中提到了这一点。完成更改后,所有对象对我来说都加载得很好(包括
地址.results[0]。格式化的\u地址
。我使用的搜索字符串是:
?地址=san%20fransisco
是的,工作得很好。太愚蠢了,我自己都想不出来。非常感谢!
address = await response.Content.ReadAsAsync<Rootobject>();
address = await response.Content.ReadAsAsync<Result>();
{
    "results" : [
     {
         "address_components" : [
         {
            "long_name" : "1600",
            "short_name" : "1600",
            "types" : [ "street_number" ]
         }]
    ...            
    }],
   "status" : "OK"
}