You need to enable JavaScript to run this app. C# WebApi接收List<MyClass>参数为空列表而非null问题排查
优惠活动
大模型
产品
解决方案
定价
更多

C# WebApi接收List<MyClass>参数为空列表而非null问题排查

问题原因及解决方案

核心问题解析

1. 缺少无参数构造函数

WebApi默认的JSON序列化器(无论是System.Text.Json还是Newtonsoft.Json)反序列化时,依赖类的无参数构造函数创建实例,再对属性赋值。你的MyClass和MyOtherClass仅定义了带参构造,序列化器无法自动实例化对象,导致列表无法解析元素,最终Count为0。

2. 只读属性无法被赋值

ID和Name属性只有get访问器,没有set(或私有set/初始化逻辑),序列化器无法将JSON中的值写入这些属性,进一步导致对象实例化失败。

3. 接口类型集合无法直接反序列化

OtherList是List<IMyOtherClass>接口类型集合,序列化器不知道要将JSON子对象反序列化为哪个具体实现类(MyOtherClass),这会导致子集合解析失败,间接影响整个对象的反序列化。


具体修复步骤

步骤1:添加无参数构造函数

给MyClass和MyOtherClass添加无参数构造函数,若业务不允许公开,可设为私有(需配合序列化器配置允许非公共构造):

public class MyClass : IMyClass
{
    // 添加无参数构造函数
    public MyClass() { }

    public MyClass(int id, string name)
    {
        ID = id;
        Name = name;
    }

    public MyClass(int id, string name, List<IMyOtherClass> otherList)
    {
        ID = id;
        Name = name;
        OtherList = otherList;
    }

    // 给只读属性添加私有set,允许序列化器赋值
    public int ID { get; private set; }
    public string Name { get; private set; }
    public List<IMyOtherClass> OtherList { get; set; }
}

public class MyOtherClass : IMyOtherClass
{
    // 添加无参数构造函数
    public MyOtherClass() { }

    public MyOtherClass(int id, string name)
    {
        ID = id;
        Name = name;
    }

    public int ID { get; private set; }
    public string Name { get; private set; }
}

步骤2:用构造函数绑定保留只读属性

如果必须保持属性只读,可通过[JsonConstructor]标记带参构造函数,告诉序列化器使用该构造实例化对象:

public class MyClass : IMyClass
{
    // 标记此构造函数供序列化器使用
    [JsonConstructor]
    public MyClass(int id, string name, List<MyOtherClass> otherList)
    {
        ID = id;
        Name = name;
        OtherList = otherList?.Cast<IMyOtherClass>().ToList();
    }

    public int ID { get; }
    public string Name { get; }
    public List<IMyOtherClass> OtherList { get; }
}

步骤3:处理接口类型集合

有两种方式解决接口集合的反序列化问题:

  • 改为具体类型集合:将List<IMyOtherClass>替换为List<MyOtherClass>,序列化器可直接解析。
  • 保留接口类型:给接口添加JsonDerivedType特性指定实现类(System.Text.Json):
    [JsonDerivedType(typeof(MyOtherClass))]
    public interface IMyOtherClass
    {
        int ID { get; }
        string Name { get; }
    }
    

关于Swagger的验证

Swagger本身不会导致该问题,你传入的JSON格式(小写键名)是正确的,序列化器默认大小写不敏感,无需调整格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:54:22