Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get C#-Object-Array out of a JSON-String

So, this is my class:

public class User
{
    public User() { }

    public string Username { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}

And this is how my JSON-String looks like:

{"results":[{"FirstName":"firstname1","LastName":"lastname1","Password":"TestPassword","Username":"TestUser","createdAt":"2015-03-02T17:36:25.232Z","objectId":"a8bKXDg2Y2","updatedAt":"2015-03-02T20:35:48.755Z"},{"FirstName":"firstname2","LastName":"lastname2","Password":"TestPw","Username":"TestUser2","createdAt":"2015-03-02T20:35:26.604Z","objectId":"2XPIklE3uW","updatedAt":"2015-03-02T20:35:53.712Z"}]}

I would like to get a User[] users out of it. My Problem is the {"results:":[....]}-Part.

I've tried it this way:

JavaScriptSerializer js = new JavaScriptSerializer();
User[] user = js.Deserialize<User[]>(jsonString);

but I think the results-Part is messing everything up somehow. What would be the best way to solve this problem?

like image 815
Dominik Seemayr Avatar asked Mar 02 '15 20:03

Dominik Seemayr


Video Answer


2 Answers

Try defining a wrapping model that will reflect your JSON structure:

public class MyModel
{
    public User[] Results { get; set; }
}

Now you can go ahead and deserialize your JSON string back to this wrapping model:

JavaScriptSerializer js = new JavaScriptSerializer();
MyModel model = js.Deserialize<MyModel>(jsonString);

and now there's nothing preventing you from getting your users collection back:

User[] user = model.Results;
like image 162
Darin Dimitrov Avatar answered Oct 24 '22 01:10

Darin Dimitrov


You need another layer on your model

public class Data
{
   public User[] results { get; set; }
}

Then deserialize the Data class

like image 45
Steve Mitcham Avatar answered Oct 24 '22 01:10

Steve Mitcham