C#控制台调用API反序列化时Country字段返回Null问题求助
问题解决:API反序列化时Country字段返回Null
核心原因
从API返回的响应结构来看,Response数组中的每个元素内的country是单个对象,但你定义的CountryResponse类将Country字段声明为List<Country>(列表类型),类型不匹配导致反序列化失败,最终返回Null。
修改方案
- 调整
CountryResponse类的字段类型
将Country字段从列表改为单个Country对象:
using APIFootballDataRetrieval.Models; namespace APIFootballDataRetrieval.Response { public class CountryResponse { // 从List<Country>改为单个Country对象 public Country Country { get; set; } } }
- 确保属性名称匹配(可选但推荐)
如果API返回的字段是驼峰命名(比如country),而你的类属性是PascalCase(Country),可以通过添加JsonProperty特性明确指定映射的字段名,避免因命名规则差异导致的映射失败:
using APIFootballDataRetrieval.Models; using Newtonsoft.Json; namespace APIFootballDataRetrieval.Response { public class CountryResponse { [JsonProperty("country")] public Country Country { get; set; } } }
同时,CountriesResponse类的字段也建议添加对应特性:
using APIFootballDataRetrieval.Models; using Newtonsoft.Json; namespace APIFootballDataRetrieval.Response { public class CountriesResponse { [JsonProperty("get")] public string Get { get; set; } [JsonProperty("response")] public List<CountryResponse> Response { get; set; } } }
- 验证反序列化结果
修改后,可添加代码验证数据是否正确映射:
// 反序列化后添加以下代码 foreach (var countryResp in CountriesResponse.Response) { if (countryResp.Country != null) { Console.WriteLine($"国家名称: {countryResp.Country.name}, 代码: {countryResp.Country.code}"); } }
额外建议
- 调试时可以将返回的JSON字符串复制到JSON转C#类工具中,自动生成匹配的类结构,避免手动定义时出现类型或字段名错误。
- 确保HttpClient请求头中的API密钥正确,避免返回异常格式的响应。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

