简体   繁体   中英

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?

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;

You need another layer on your model

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

Then deserialize the Data class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM