1

How can I cast my WebClient JSON response to list of objects that represents the json response? For example, I have the following JSON:

{
    "posts" [
        { 
           "content": "Hello world",
           "user" : {
                "id": 5,
                "username": "foo"
           }
        }, 
        { 
           "content": "Foobar",
           "user" : {
                "id": 3,
                "username": "baz"
           }
        }, 
    ]
}

And I have 2 classs:

class Post
{
     public string Content;
     public User User;
}
class User
{
     public int Id;
     public string Username;
}

Now I want to send a request with WebRequest and cast my JSON response to list of those Posts. How can I do that?

Videron
  • 171
  • 1
  • 3
  • 11

1 Answers1

2

The easiest way is to let a JSON library deserialize the response to the target object:

var posts = JsonConvert.DeserializeObject<List<Post>>(responseText);
twoflower
  • 6,788
  • 2
  • 33
  • 44