I have a JSON file with products in it sorted by categories. I’m trying to deserialize the JSON so I get a List<List> so I can access easily for example the products inside "Favorites".
I saw a problem on using JSON because I also need the categories names and I’m right now storing them inside the product itself. What I’m trying to achieve is to easily get all the products stored inside "Favorites" or another one.
My main problem here is that I’m not sure what kind of data type is better to store this kind of information. My JSON is:
{
"Favoritos": [
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Hombre",
"Precio" : "10,00",
"Color" : "57; 62; 65"
},
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Mujer",
"Precio" : "100,00",
"Color" : "57; 62; 65"
}
],
"CortePelo": [
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Hombre",
"Precio" : "10,00",
"Color" : "57; 62; 65"
},
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Mujer",
"Precio" : "100,00",
"Color" : "57; 62; 65"
}
]
}
My Classes are:
public class Productos
{
public List<List<Producto>> Categorias { get; set; }
}
public class Producto
{
public string Categoria { get; set; }
public string Nombre { get; set; }
public double Precio { get; set; }
public string Color { get; set; }
[JsonConstructor]
public Producto(string categoria, string nom, double prc, string color)
{
Categoria = categoria;
Nombre = nom;
Precio = prc;
Color = color;
}
}
And I’m getting null on the deserialization doing:
string json = r.ReadToEnd();
Productos productos = JsonConvert.DeserializeObject<Productos>(json);
>Solution :
Your JSON does not match the schema defined in Productos. Instead of using that Productos class, use Dictionary<string,Producto[]> instead which better matches the JSON.
Like so:
string json = r.ReadToEnd();
Dictionary<string,Producto[]> productosPorCategoria = JsonConvert.DeserializeObject<Dictionary<string,Producto[]>>(json);
Note: I’m sorry if I got the variable name incorrect, I used Google Translate for that bit.
If you’d still like to strongly type the properties instead of using a Dictionary, you’ll need to update Productos like so:
public class Productos
{
public List<Producto> Favoritos { get; set; }
public List<Producto> CortePelo { get; set; }
}