调用返回对象数组的API时无法反序列化为Bike类该如何解决
问题原因
- 接口返回的是JSON数组结构,但你最初的代码尝试将数组反序列化为单个
Bike对象,类型不匹配触发报错。如果你尝试过集合类型仍然报错,大概率是没有同步修改方法返回值、接收变量的类型,或是Bike类的属性定义和JSON字段不匹配。 - 原有代码存在变量名笔误:点击事件中声明的变量是
bikeInfo,但实际使用了未定义的wlrInfo变量。 - 重复给
BikeinfoBox.Text赋值会覆盖之前的内容,最终仅会显示最后一行的赋值结果。
修复方案
步骤1:修改LoadData方法,适配数组返回
// 方法返回值修改为List<Bike>集合 public static async Task<List<Bike>> LoadData() { string url = "/Bikes?take=100"; // 已配置BaseAddress可直接使用相对地址 using (HttpResponseMessage response = await API_helper.ApiClient.GetAsync(url)) { if (response.IsSuccessStatusCode) { // 反序列化为List<Bike>集合 List<Bike> bikes = await response.Content.ReadAsAsync<List<Bike>>(); return bikes; } else { throw new Exception(response.ReasonPhrase); } } }
步骤2:修改按钮点击事件逻辑
private async void button1_Click(object sender, System.EventArgs e) { // 接收返回的集合 var bikeList = await DataProcessor.LoadData(); // 示例:取第一辆自行车的信息展示,也可根据需求遍历集合 if(bikeList.Any()) { var firstBike = bikeList[0]; // 拼接内容避免覆盖 BikeinfoBox.Text = $"Bike Nummer {firstBike.bikeID}\n"; BikeinfoBox.Text += $"Naam is {firstBike.name}\n"; BikeinfoBox.Text += $"ShopID is {firstBike.StoreID}"; } }
步骤3:若仍反序列化失败,检查Bike类定义
确保Bike类的属性和JSON字段大小写匹配,或配置序列化规则忽略大小写,示例类定义如下:
public class Bike { public int bikeID { get; set; } public int manuid { get; set; } public string name { get; set; } public int StoreID { get; set; } }
内容的提问来源于stack exchange,提问作者Tim Verhees
相关产品推荐
相关产品推荐

