【问题标题】:Calling JSON Array from an API that contains objects从包含对象的 API 调用 JSON 数组
【发布时间】:2021-10-31 18:31:47
【问题描述】:

我正在尝试从其数据结构如下的 API 检索数据:

[
  {
    "bikeID": 5,
    "manuid": 168,
    "name": "Gran",
    "StoreID": 2
  }
]

现在我尝试使用适当的 URL 从 API 中检索数据:

public static class API_helper
{
    public static HttpClient ApiClient { get; set; }

    public static void InitializeClient()
    {
        ApiClient = new HttpClient();
        ApiClient.BaseAddress = new Uri("http://api.----------");
        ApiClient.DefaultRequestHeaders.Accept.Clear();
        ApiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
        ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
}

public static async Task<Bike> LoadData()
{
    string url = "http://api.----------/Bikes?take=100";
    using (HttpResponseMessage response = await API_helper.ApiClient.GetAsync(url))
    {
        if (response.IsSuccessStatusCode)
        {
            Bike bike  = await response.Content.ReadAsAsync<Bike>();
            return bike;
        }
        else
        {
            throw new Exception(response.ReasonPhrase);
        }
    }
}

private async void button1_Click(object sender, System.EventArgs e)
{
    var bikeInfo = await DataProcessor.LoadData();

    BikeinfoBox.Text = $"Bike Nummer { wlrInfo.BikeID}";
    BikeinfoBox.Text = $"Naam is {wlrInfo.Name}";
    BikeinfoBox.Text = $"ShopID is { bikeInfo.StoreID}";
}

但继续得到列出以下的错误。

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“DHM_test_2.Bike”,因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。 JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组反序列化。 路径'',第 1 行,位置 1。

我尝试了通过 IList、List 和 ICollection 将其设为列表的各种其他方法,但似乎都不起作用。那么如何确保它返回一个数组呢?

【问题讨论】:

  • var bikes = await response.Content.ReadAsAsync&lt;List&lt;Bike&gt;&gt;();怎么样
  • 然后,在返回语句中它说“错误 CS0029 无法将类型 'System.Collections.Generic.List' 隐式转换为 'DHM_test_2.Bike'”
  • 嗯,这是一个列表,显然你需要决定你想要从中得到什么。您只想要第一个项目,还是如果有 0 个或多个项目怎么办?
  • @Charlieface 嗯,第二、三、四项。
  • 然后你去返回它们,你需要将你的函数的返回类型更改为Task&lt;List&lt;Bike&gt;&gt;

标签: c# arrays json api


【解决方案1】:

返回类型为数组,尝试用Bike[]反序列化

Bike[] bikes = await response.Content.ReadAsAsync<Bike[]>();

【讨论】:

  • 具体在哪里?因为这似乎没有任何作用。
  • 等等什么?也许你需要用更多的词
  • 哦,谢谢您编辑我的回复,我失去了评论...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 2013-10-02
  • 2015-06-11
  • 2021-09-22
相关资源
最近更新 更多