Get C # -Object-Array from 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 here is what 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 want the user User [] to be from it. My problem is {"results:": [....]} - Part.

I tried it like this:

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

but I think the Part-Part will somehow ruin everything. What would be the best way to solve this problem?

+6
source share
2 answers

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

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

Now you can continue and deserialize the JSON string back to this packaging model:

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

and now nothing prevents you from returning your user collection:

 User[] user = model.Results; 
+7
source

You need another layer on your model

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

Then deserialize the Data class

+1
source

Source: https://habr.com/ru/post/983236/


All Articles