C#:JSON的反序列化会导致空列表吗



我试图反序列化到我的自定义AccountList类来处理嵌套的JSON,但Accounts列表总是空的?

方法:

public T GetJsonForEndpoint<T>(string endpoint)
{
var request = new RestRequest(endpoint);
var queryResult = _client.Get(request);
var data = JsonConvert.DeserializeObject<T>(queryResult.Content);
return data;
}

JSON:

{
"accounts": [
{
"id": 435453435,
"forename": "John",
"surname": "Doe"
},
{
"id": 2321323234,
"forename": "Jane",
"surname": "Doe"
}
]
}

类别:

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

由于您既没有提供setter也没有初始化列表,所以序列化程序可能只是忽略它(它不能将它设置为非null,也不能向它添加元素(。

拥有不可变的集合引用通常是一个更好的主意,所以我建议您这样初始化列表:

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

我还建议避免使用自定义[JsonProperty("accounts")],而是根据文档将序列化程序配置为在其配置中尊重camelCasing:

  • https://www.newtonsoft.com/json/help/html/NamingStrategyCamelCase.htm

最新更新