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

C#中JSON反序列化后Accounts列表始终为null的问题

解决JSON反序列化后Accounts列表为null的问题

问题原因

你的AccountList类中Accounts属性仅定义了只读的get访问器,Json.NET(Newtonsoft.Json)无法为这类只读集合属性赋值,因此反序列化完成后该属性始终为null。

解决方案

方案1:为属性添加可写访问器

修改AccountList类,给Accounts属性添加set访问器,让Json.NET能正常赋值:

public class AccountList
{
    [JsonProperty("accounts")]
    public List<Dictionary<string, string>> Accounts { get; set; }
}

方案2:使用强类型类替代字典(更推荐)

JSON中的每个账户结构固定,用强类型类映射比Dictionary<string, string>更安全,还能避免数值类型(如id)转字符串的潜在问题:

// 定义Account类映射单个账户结构
public class Account
{
    [JsonProperty("id")]
    public long Id { get; set; }
    [JsonProperty("forename")]
    public string Forename { get; set; }
    [JsonProperty("surname")]
    public string Surname { get; set; }
}

// 修改AccountList类使用强类型集合
public class AccountList
{
    [JsonProperty("accounts")]
    public List<Account> Accounts { get; set; }
}

补充说明

Json.NET反序列化时,需要目标属性具备可访问的set方法(或者通过构造函数注入属性值)才能完成赋值。仅含get的只读属性无法被框架修改,会保持初始的null状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:45:38