6

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?

1
  • 2
    Whenever you have the JSON I always recommend going to json2csharp.com. It will generate the classes you need to deserialize into. Commented Mar 2, 2015 at 20:44

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

3 Comments

thank you, this might work - but is is a good way to create a wrapper for every class?
Of course that it is a good way. You must match exactly the JSON structure you are deserializing. Otherwise how do you expect a JSON serializer to automagically know what you are trying to achieve? It works by type introspection and properties matching. So make sure you have the proper structure when serializing/deserializing.
Thank you very much! Helped me a lot. (I need to wait about 7 minutes to accept this answer, I'll do it later)
1

You need another layer on your model

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

Then deserialize the Data class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.