Parse json string to a class populating it's subclasses

116 views Asked by At

I have this string returned to my code behind:

string json = "[[{'nome':'joe','cpf':'54'},{'id':'8','nome':'Legendagem','valor':'5'}],[{'nome':'jane','cpf':'22'},{'id':'1','nome':'Legendagem2','valor':'6'}]]";

and I have 3 classes:

public class ItemCart
{
    public UserCart user { get; set; }
    public CursoCart curso { get; set; }
}


public class UserCart
{
    public string nome { get; set; }
    public string email { get; set; }
    public string cpf { get; set; }
}

public class CursoCart
{
    public string id { get; set; }
    public string desc { get; set; }
    public string valor { get; set; }
}

what i want is to have the class UserCart/CursoCart class populated so I can loop inside itemCart and get the values, length etc of the UserCart/CursoCart items eg:

UserCart user1 = itemCart[0].user;

supposing that I can't change the string, I'm trying this to convert, but now working:

List<ItemCart> itemCart = JsonConvert.DeserializeObject<List<ItemCart>>(json);

thank you for any help.

1

There are 1 answers

0
zapoo On BEST ANSWER

As I see from your json it is an array. The following ItemCart and Deserialization may work for you.

public class Program
{
    public static void Main()
    {
        string json = "[[{'nome':'joe','cpf':'54'},{'id':'8','nome':'Legendagem','valor':'5'}],[{'nome':'jane','cpf':'22'},{'id':'1','nome':'Legendagem2','valor':'6'}]]";
        var ItemCartList = JsonConvert.DeserializeObject<List<Item[]>>(json);

    }
}

public class ItemCart
{
    public Item[][] ItemList { get; set; }
}

public class Item
{
    public string nome { get; set; }
    public string cpf { get; set; }
    public string id { get; set; }
    public string valor { get; set; }
}