A. Vreeswijk
A. Vreeswijk

Reputation: 954

C# Convert json to multiple classes

I have a problem. I am trying to parse my json to 2 classes. Here is the json:

{
   "user":[
      [
         {
            "Id":"0",
            "Username":"Vreeswijk",
            "ProfilePicture":"media/user/0.png"
         }
      ]
   ],
   "token":[
      [
         {
            "access_token":"myToken1",
            "refresh_token":"myToken2",
            "expires_in":3600,
            "expires_on":1577363756
         }
      ]
   ]
}

And here are my 2 classes:

public class Token
{
    public string access_token { get; set; }
    public string refresh_token { get; set; }
    public int expire_in { get; set; }
    public int expire_on { get; set; }

    public Token() { }
}

And here is the user class:

public class User
{
    [PrimaryKey]
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string ProfilePicture { get; set; }

    public User() { }
    public User(string Username, string Password)
    {
        this.Username = Username;
        this.Password = Password;
    }
}

Now I want to deserialize the json to those 2 classes. Here is my code now that works for 1 class only:

var jObject = JObject.Parse(json);
var userPropery = jObject["user"] as JArray;
userList= new List<user>();

foreach (var property in userPropery )
{
    var propertyList = JsonConvert.DeserializeObject<List<user>>(property.ToString());

    userList.AddRange(propertyList);
}

How can I make this work for 2 classes in 1 json?

Upvotes: 4

Views: 3080

Answers (3)

Anu Viswan
Anu Viswan

Reputation: 18153

If you observe your Json, both user and token are nested Arrays. You can now create Root Class that has both the required properties. For Example

public class Root
{
    public List<List<User>> user { get; set; }
    public List<List<Token>> token { get; set; }
}

Now, instead of using JObject.Parse you could deserialize it directly as

var root = JsonConvert.DeserializeObject<Root>(json);

To get a flattened user and token list, you can use

var userList= root.user.SelectMany(x=>x); 
var tokenList= root.token.SelectMany(x=>x); 

Upvotes: 1

Nguyen Van Thanh
Nguyen Van Thanh

Reputation: 825

Why don't you create a class include both user and token? If you don't do this, please parse one by one.

Upvotes: 0

stud3nt
stud3nt

Reputation: 2143

You can create a Root class for your json and add two properties in it with User and Token classes as required.

public class Root
{
    public List<List<User>> Users { get; set; }
    public List<List<Token>> Tokens { get; set; }
}

Then pass this class in DeserializeObject function to deserialize the json.

Upvotes: 1

Related Questions