skip to Main Content

I’m trying to parse a JSON response which looks like this:

{
    "users" : [{id: 1, ...},{id: 2, ...}],
    "count": 200
}

into List of Users using C#. I’ve tried parsing it this way:

Dictionary<string, List<User>> parsedJson = JsonConvert.DeserializeObject<Dictionary<string, List<User>>>(result);

but got an error indicating that (count:100) can not be parsed.
Now I am able to get the result using

Dictionary<string, dynamic> parsedJson = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(result);

but I want to be sure that parsedJson["users"] is going to be a List of User. How can I achieve that?

2

Answers


  1. Your JSON response is an object with two properties, so you should try:

    public class JsonResponseDto
    {
        public List<User> Users { get; set; }
        public int Count {get; set; }
    }
    
    var deserializedResult = JsonConvert.DeserializeObject<JsonResponseDto>(result);
    
    Login or Signup to reply.
  2. You don’t need any extra class

    List<User> users = JObject.Parse(result)["users"].ToObject<List<User>>(); 
    

    and if you need count

    int count = users.Count;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search