You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC调用Web API获取JSON反序列化后Student列表为空值问题

问题解决:反序列化JSON返回空值的修复方案

核心问题分析

你的代码出现空值的原因有两个:

  1. JSON结构与C#类型不匹配:返回的JSON是一个包含单个对象的数组,这个对象内部才有Students数组;而你直接尝试反序列化为List<Student>,完全对应不上结构。
  2. 属性名称大小写不匹配:JSON中字段是小写的id/name/department,但C#类中是大写开头的Id/Name/Department,默认序列化规则不会自动映射这些大小写不同的字段。

修复步骤

1. 定义匹配JSON结构的根类

首先需要创建一个根类来对应JSON的最外层结构:

public class StudentRoot
{
    public List<Student> Students { get; set; }
}

2. 处理属性名称映射(二选一)

方式一:手动指定JsonProperty属性

修改Student类,为每个属性加上JsonProperty特性,明确对应JSON中的字段名:

public class Student
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("department")]
    public string Department { get; set; }
}

方式二:配置序列化器忽略大小写

如果不想逐个加特性,可以配置Json.NET使用驼峰命名解析器,自动匹配大小写:

var serializerSettings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

3. 修改反序列化代码

调整GetAllStudents方法,先反序列化为根对象数组,再提取Students列表:

[HttpGet]
public async Task<List<Student>> GetAllStudents()
{
    var oStudents = new List<Student>();
    using (var httpclient = new HttpClient())
    {
        using (var response = await httpclient.GetAsync("https://localhost:7232/api/Student"))
        {
            string res = await response.Content.ReadAsStringAsync();
            
            // 使用方式一的映射时,直接反序列化
            var rootList = JsonConvert.DeserializeObject<List<StudentRoot>>(res);
            
            // 如果用方式二的配置,就传入settings
            // var rootList = JsonConvert.DeserializeObject<List<StudentRoot>>(res, serializerSettings);
            
            if (rootList?.Any() == true)
            {
                oStudents = rootList.First().Students;
            }
        }
    }
    return oStudents;
}

验证逻辑

修复后,反序列化会先解析外层的数组,取出第一个对象中的Students数组,同时正确映射每个学生的字段值,最终就能得到非空的学生列表用于表格展示。

内容的提问来源于stack exchange,提问作者Tanmay Pawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:58:03