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

使用Json.NET反序列化JSON至自定义对象时遇构建及运行时错误

问题解决方法

你遇到的问题是将Items属性的setter改为私有后,Json.NET无法正确初始化这个集合属性,导致运行时Items为null。可以通过以下几种方式解决:

方案1:初始化只读集合

直接在属性声明时初始化集合为具体实现类,同时去掉setter,完全符合“只读”要求:

public class WorkingSetContent
{
    /// <summary>Collection ID</summary>
    [JsonProperty("context")]
    public string Context { get; set; }

    /// <summary>UserRelationship</summary>
    [JsonProperty("value")]
    public IList<ItemClass> Items { get; } = new List<ItemClass>();
}

Json.NET会自动将JSON中的value数组元素添加到这个已初始化的集合中,不需要setter。

方案2:用具体集合类型+私有setter

如果需要保留私有setter,把属性类型从IList<ItemClass>改为具体的List<ItemClass>,并预先初始化:

public class WorkingSetContent
{
    /// <summary>Collection ID</summary>
    [JsonProperty("context")]
    public string Context { get; set; }

    /// <summary>UserRelationship</summary>
    [JsonProperty("value")]
    public List<ItemClass> Items { get; private set; } = new List<ItemClass>();
}

这样Json.NET能明确知道要实例化的集合类型,即使setter私有也能正确赋值。

方案3:构造函数初始化集合

在类的构造函数里初始化集合,搭配私有setter使用:

public class WorkingSetContent
{
    public WorkingSetContent()
    {
        Items = new List<ItemClass>();
    }

    /// <summary>Collection ID</summary>
    [JsonProperty("context")]
    public string Context { get; set; }

    /// <summary>UserRelationship</summary>
    [JsonProperty("value")]
    public IList<ItemClass> Items { get; private set; }
}

这种方式也能确保集合在反序列化前已被初始化,Json.NET会直接往集合里添加元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:20:37