Videron
Videron

Reputation: 179

WebClient response to list of object

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?

Upvotes: 1

Views: 2156

Answers (1)

twoflower
twoflower

Reputation: 6830

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

var posts = JsonConvert.DeserializeObject<List<Post>>(responseText);

Upvotes: 2

Related Questions