Reputation:
I'm trying to deserialize to my custom AccountList
class to deal with the nested JSON but the Accounts
list is always null?
Method:
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"
}
]
}
Class:
public class AccountList
{
[JsonProperty("accounts")]
public List<Dictionary<string, string>> Accounts { get; }
}
Upvotes: 1
Views: 917
Reputation: 8181
Since you have neither provided a setter nor initialized your list, the serializer is probably just ignoring it (it can't set it to something non-null, or add elements to it).
It is usually a better idea to have immutable collection references, so I'd recommend just initializing your list like this:
public class AccountList
{
[JsonProperty("accounts")]
public List<Dictionary<string, string>> Accounts { get; } = new();
}
I'd also recommend avoiding the custom [JsonProperty("accounts")]
and instead configure the serializer to respect camelCasing in its configuration as per the documentation:
Upvotes: 3