You need to enable JavaScript to run this app. 为什么C#中Json.NET序列化自定义对象集合时返回空数组?
优惠活动
大模型
产品
解决方案
定价
更多

为什么C#中Json.NET序列化自定义对象集合时返回空数组?

序列化输出空数组问题排查与修复

问题根因

你当前的类定义存在逻辑错误,直接导致序列化行为完全偏离预期:

  • 定义的CustomCommands类直接继承了List<CustomCommands>,意味着这个类本身就是一个集合类型
  • Newtonsoft.Json序列化器遇到实现了IEnumerable接口的类型时,会优先将其作为集合处理,只会遍历输出集合内部存储的元素,完全忽略类上标记了[JsonProperty]的普通属性
  • 你传入序列化的每个CustomCommands实例,其作为集合基类的内部并没有存储任何嵌套元素,因此序列化时只会输出空数组[],最终拼出的JSON就是两个空数组组成的外层集合
  • 你感知到“单独序列化单个对象时运行正常”,本质是之前的测试没有验证序列化结果是否真的包含自定义属性——实际序列化单个对象时,同样只会输出空数组,根本没有把CommandName等属性写入JSON

修复步骤

1. 修正错误的类继承

实体类不需要继承集合类型,直接定义为普通POCO类即可:

public class CustomCommands
{
    [JsonProperty]
    public string CommandName { get; set; }
    [JsonProperty]
    public string CommandResponse { get; set; }
    [JsonProperty]
    public bool IsModCommand { get; set; }

    public static void SaveCommands(List<CustomCommands> CommandsList, string FileName)
    {
        string JsonString = JsonConvert.SerializeObject(CommandsList, Newtonsoft.Json.Formatting.Indented);
        File.WriteAllText(FileName, JsonString);
    }

    public static List<CustomCommands> LoadCommands(string FileName)
    {
        string JsonString = File.ReadAllText(FileName);
        // 修正反序列化的泛型参数,匹配返回值类型
        return JsonConvert.DeserializeObject<List<CustomCommands>>(JsonString);
    }
}

2. 修正反序列化的泛型参数

原代码中LoadCommands方法的反序列化目标类型写为CustomCommands,和方法要返回的List<CustomCommands>类型不匹配,会直接导致类型转换异常,需要将泛型参数改为List<CustomCommands>。
修改完成后,序列化器就会正常识别每个实例的自定义属性,输出包含完整字段的JSON对象,而不是空数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.04 01:15:03