ASP.NET MVC中如何将API返回的JSON数组反序列化为List
ASP.NET MVC中JSON数组反序列化为List的解决方案
你的核心问题是API返回的JSON结构和你直接反序列化的目标类型不匹配:API返回的是一个包含data字段的对象,而非直接的数组,所以直接用JsonConvert.DeserializeObject<List<Country>>会失败。以下是修正步骤:
1. 创建JSON结构对应的包装类
先定义一个和API返回JSON结构一致的类,用来接收完整的响应:
public class CountryResponse { public List<Country> Data { get; set; } }
2. 修正Controller中的反序列化逻辑
同时优化异步代码(避免使用.Result,改用await保证异步流程正确):
public async Task<IActionResult> ListCountries() { List<Country> countries = new List<Country>(); using (HttpClient _client = _apiHelper.Initial()) // 使用using自动释放资源 { HttpResponseMessage _response = await _client.GetAsync("api/Countries/getall"); if (_response.IsSuccessStatusCode) { var results = await _response.Content.ReadAsStringAsync(); var response = JsonConvert.DeserializeObject<CountryResponse>(results); countries = response.Data ?? new List<Country>(); // 空值判断避免空引用 } } return View(countries); }
3. (可选)明确实体类的字段映射
如果需要更严谨的字段匹配,可以给Country类添加JsonProperty特性,确保和JSON中的字段名完全对应:
public class Country { [Key] [JsonProperty("id")] public int Id { get; set; } [JsonProperty("countryName")] public string CountryName { get; set; } }
4. 在页面中使用List
确保你的View(比如ListCountries.cshtml)的模型类型是List<Country>,就可以直接遍历展示数据:
@model List<Country> <h1>国家列表</h1> <ul> @foreach (var country in Model) { <li>@country.Id - @country.CountryName</li> } </ul>
内容的提问来源于stack exchange,提问作者mustafasamet
相关产品推荐
相关产品推荐

