.NET Core 5调用AniAPI接口GET请求JSON反序列化报错如何解决
错误原因
- 你调用的
https://api.aniapi.com/v1/anime接口返回的JSON最外层是单个响应对象,而非ApiAnime类型的数组,直接反序列化为IEnumerable<ApiAnime>会出现类型不匹配错误。 - 你当前的实体类嵌套结构不合理,实际的动画数据存放在根对象下
data.documents层级,你之前的反序列化逻辑没有对应到正确的层级。 - 缺失
Titles、Descriptions两个实体类定义,也会导致反序列化失败。
修复步骤
1. 调整实体类定义
将嵌套的实体类拆分,补全缺失的类型,可按需将值类型改为可空避免空值报错:
public class Titles { public string en { get; set; } public string jp { get; set; } // 按需补充其他语种字段 } public class Descriptions { public string en { get; set; } public string jp { get; set; } // 按需补充其他语种字段 } public class AniApiResponse { public int status_code { get; set; } public string message { get; set; } public AniApiData data { get; set; } public string version { get; set; } } public class AniApiData { public int current_page { get; set; } public int count { get; set; } public List<ApiAnime> documents { get; set; } public int last_page { get; set; } } public class ApiAnime { public int anilist_id { get; set; } public int mal_id { get; set; } public int format { get; set; } public int status { get; set; } public Titles titles { get; set; } public Descriptions descriptions { get; set; } public DateTime? start_date { get; set; } public DateTime? end_date { get; set; } public int season_period { get; set; } public int season_year { get; set; } public int episodes_count { get; set; } public int episode_duration { get; set; } public string trailer_url { get; set; } public string cover_image { get; set; } public string cover_color { get; set; } public string banner_image { get; set; } public string[] genres { get; set; } public int score { get; set; } public int id { get; set; } public int? prequel { get; set; } public int? sequel { get; set; } }
2. 修改Razor页面的反序列化逻辑
先反序列化接口返回的根对象,再提取对应层级的动画列表:
public class IndexModel : PageModel { public IEnumerable<ApiAnime> ApiData { get; set; } public async Task<IActionResult> OnGet() { var request = new HttpRequestMessage(HttpMethod.Get, "https://api.aniapi.com/v1/anime"); var client = _clientFactory.CreateClient(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var responseStream = await response.Content.ReadAsStreamAsync(); // 配置反序列化规则,不区分属性名大小写 var serializeOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var apiResult = await JsonSerializer.DeserializeAsync<AniApiResponse>(responseStream, serializeOptions); ApiData = apiResult?.data?.documents ?? Enumerable.Empty<ApiAnime>(); } else { ApiData = Enumerable.Empty<ApiAnime>(); } return Page(); } }
注意事项
- 如果接口返回的日期格式不兼容System.Text.Json的默认规则,可以在
JsonSerializerOptions中添加自定义的DateTime转换器处理格式问题。 - 若后续需要处理分页逻辑,可以直接读取
AniApiResponse.data下的current_page、last_page等字段实现分页逻辑。
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

