I need to deserialize a JSON that is recursive in C# (.Net 5.0). It is for a software that should be able to read JSON's from this type into an object and later display it. My problem is that I don't know how I can read recursive JSON's with changeable keys.
This is an example with animals:
{
"mammal":
{
"id": 1,
"name": "a",
"age": 22,
"human":
{
"id": 1,
"name": "o",
"age": 22
},
"squirrel":
{
"id": 2,
"name": "p",
"age": 22
}
},
"reptile":
{
"id": 2,
"name": "u",
"age": 22
},
"bird":
{
"id": 3,
"name": "x",
"age": 22
}
}
The classes for that are:
public class AnimalsJsonFile {
public string Path;
public Dictionary<string, AnimalData> AnimalDictionary;
}
public class AnimalData {
public int Id;
public string Name;
public int Age;
public Dictionary<string, AnimalData> AnimalDictionary;
}
So as you can see, the key in the JSON changes because it describes the name/type, while the attributes always have the same key. That's why I wanted to use a dictionary with the key as string that references onto its data as AnimalData. Also, every "animal" can contain another animal, and so on. The variable path, in the class AnimalsJsonFile, is used to save the path from the JSON file. Is there any way to deserialize any JSON from this type I have shown into my AnimalsJsonFile class?
I currently use Newtonsoft to deserialize another file type. Thanks for your help.