d45ndx d45ndx - 4 years ago 462
C# Question

C# JsonConvert.DeserializeObject to list / add item to array

I'm currently trying to add a item to a array. But I think a list would be way easier since I could use

list.Add("whatever");


Is there a way to receive the following as a list?

dynamic reps = JsonConvert.DeserializeObject("rep.json");


Example json:

{"reps": {
{
"username": "usera",
"reps": 10,
"latestrep": "userx"
},
"userb": {
"username": "userb",
"reps": 10,
"latestrep": "userx"
},
"userc": {
"username": "userc",
"reps": 10,
"latestrep": "userx"
}
}}


I appreciate any kind of help

Answer Source

Providing you have a class defining the list item:

public class UserReps
{
    public string Username { get; set; }
    public int Reps { get; set; }
    public string LatestRep { get; set; }
} 

You can achieve what you want with LINQ:

IDictionary<string, IDictionary<string, UserReps>> parsed = JsonConvert.DeserializeObject<IDictionary<string, IDictionary<string, UserReps>>>(json);
List<UserReps> userReps = parsed["reps"].Select(ur => ur.Value).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download