使用Refit调用PokeAPI后出现响应反序列化错误该如何解决?
错误根因
- 你定义的
PokeResponse类结构和PokeAPI的实际返回结构完全不匹配:接口返回的根字段没有pokemon属性,你需要的能力字段abilities是嵌套数组结构,你完全没有定义对应映射。 id字段在API返回中是数字类型,你定义为string导致类型不匹配,直接触发反序列化失败。- 如果你使用的是.NET 6+默认的System.Text.Json序列化器,
[JsonProperty]是Newtonsoft.Json的专属特性,需要替换为[JsonPropertyName]才能正确映射字段。
修复方案
1. 修正PokeResponse.cs结构
根据接口返回的JSON结构调整实体类定义,补充嵌套的能力字段:
// 如果你用Newtonsoft.Json就保留下面的引用,用系统默认System.Text.Json的话换成 using System.Text.Json.Serialization; using Newtonsoft.Json; namespace Pokedex { public class PokeResponse { // 用System.Text.Json的话这里改成 [JsonPropertyName("id")],下方其他特性同理替换 [JsonProperty("id")] public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("abilities")] public List<AbilityItem> Abilities { get; set; } } public class AbilityItem { [JsonProperty("ability")] public AbilityInfo Ability { get; set; } } public class AbilityInfo { [JsonProperty("name")] public string AbilityName { get; set; } [JsonProperty("url")] public string AbilityUrl { get; set; } } }
2. 调整Program.cs的业务逻辑
补充输入校验、异常分类捕获,以及能力字段的打印逻辑:
namespace Pokedex { class Program { static async Task Main(string[] args) { try { var pokemonClient = RestService.For<IPokeApiService>("https://pokeapi.co/api/v2"); Console.WriteLine("请输入宝可梦英文名称(例如pikachu):"); string informedPokemon = Console.ReadLine()?.ToLower() ?? string.Empty; if (string.IsNullOrWhiteSpace(informedPokemon)) { Console.WriteLine("输入不能为空"); return; } Console.WriteLine($"正在查询 {informedPokemon} 的信息..."); var poke = await pokemonClient.GetPokemonAsync(informedPokemon); Console.WriteLine($"\n宝可梦编号:{poke.Id}"); Console.WriteLine($"宝可梦名称:{poke.Name}"); Console.WriteLine("能力列表:"); foreach (var item in poke.Abilities) { Console.WriteLine($"- {item.Ability.AbilityName}"); } Console.ReadKey(); } catch (HttpRequestException) { Console.WriteLine("错误:查询的宝可梦不存在,请检查输入名称是否正确"); } catch (Exception e) { Console.WriteLine("查询出错:" + e.Message); } } } }
3. 调整IPokeApiService定义
可选调整方法名让语义更清晰,不修改也可正常运行:
namespace Pokedex { public interface IPokeApiService { [Refit.Get("/pokemon/{pokemon}")] Task<PokeResponse> GetPokemonAsync(string pokemon); } }
注意事项
PokeAPI仅支持小写英文名称查询,输入中文名或拼写错误会返回404错误,已在代码中做了单独捕获提示。
内容的提问来源于stack exchange,提问作者user15270486
相关产品推荐
相关产品推荐

