Search code examples
c#jsonclassoopdeserialization

Deserialize by automatically splitting for each element of a sublist in C#


It is possible that an answer to this exist but I don't really know how to explain my problem so I'll do it here.

Let's imagine I am grabbing datas from an api in a JSON format. Let's say it has the following format :

    {
        "name": "Animals",
        "className": "Mammals",
        "speciesList": [
            {
                "species": "Panthera leo",
                "subspecies": "leo"
            },
            {
                "species": "Equus quagga",
                "subspecies": "quagga"
            }
        ]
    }

And I want to store them in the following class :

public class Animal
{
   public string name {get; set;}
   public string className {get; set;}
   public string species {get; set;}
   public string subspecies {get; set;}
}

How can I deserialize it with a class so that it creates me 2 objects, as follows :

Animal("Animals", "Mammals", "Panthera leo", "leo")
Animal("Animals", "Mammals", "Equus quagga", "quagga")

I know that I can extract all but wanted to know if there was a direct way to create this ! Thanks in advance !


Solution

  • since you want to place all code inside of one class, you can consider this

    List<Animal> animals = JsonConvert.DeserializeObject<Animals>(json).SpeciesList;
    
    public class Animals
    {
        public List<Animal> SpeciesList { get; init; }
    
        public Animals(string name, string className, List<Animal> speciesList)
        {
            speciesList.ForEach(x =>
            {
                x.name = name;
                x.className = className;
            });
            SpeciesList = speciesList;
        }
    }