Home > Net >  Deserialize JSON by Categories in C#
Deserialize JSON by Categories in C#

Time:03-25

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);

CodePudding user response:

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; }
}

CodePudding user response:

You are getting null because desearlization failed. But it did not throw exeption.

The correct type is Dictionary<string, Producto[]>

if you want to check that your desearilation is correct, first create a serialize json object of your object structure.

CodePudding user response:

Hi how about you make a list of Producto and serialize those into the json, Upon retrieval you just deserialize the json into a list and then group the list of Producto by Categoria, now you can access the list of list of products grouped by Categoria using LINQ.

{
   [
        {"Categoria" : "CortePelo",
            "Nombre" : "Corte Hombre",
            "Precio" : "10,00",
            "Color" : "57; 62; 65"
        },{
            "Categoria" : "CortePelo",
            "Nombre" : "Corte Mujer",
            "Precio" : "100,00",
            "Color" : "57; 62; 65"
        },{
            "Categoria" : "CortePelo",
            "Nombre" : "Corte Hombre",
            "Precio" : "10,00",
            "Color" : "57; 62; 65"
        },{
            "Categoria" : "CortePelo",
            "Nombre" : "Corte Mujer",
            "Precio" : "100,00",
            "Color" : "57; 62; 65"
        }
   ]
}

Here you deserialize the json to a list of Producto

string json = r.ReadToEnd();
List<Producto>productos = JsonConvert.DeserializeObject<List<Producto>>(json);

//Here you now group the list of Producto by Categoria
var groupedProductos=productos.GroupBy(x=>x.Categoria);

//To find Products with Categoria 'CortePelo'
var cortePeloGroup=groupedProductos.FirstOrDefault(x=>x.Key=="CortePelo");

//Now you convert the Grouped Producto of Categoria 'CortePelo' to List
List<Producto> cortePeloProductoList = cortePeloGroup.Select(g => g).ToList();

  • Related