I am learning the Newtonsoft JSON library in C#.
I have a class called "enemy" that descends from the "Ente" class. I have a list of type "Ente". In this list I add some instances of the "enemy" class and serialize the list, all correct. Then, with the list empty, I read the JSON file from disk, deserialize it and assign the result to the list of type "Ente". All correct but ... enemy objects are created using the constructor of the class "Ente", this is the problem, the objects should be created by calling the constructor of the class "Enemy", that is to say, objects "Enemy" must be created and not "Ente" objects.
**Edit 1:
I have other classes that also descend from "Ente" and the instances must be saved in the "EnteList" list. For example, these are other classes that descend from "Ente":
Enemy: Ente
BallOfFire: Ente
Troll: Ente
etc...
In the example I simplified it to the maximum and thought that it was not necessary to give that information. I think the newtonsoft library should do this automatically because I am specifying to save the object type that is in the list in the JSON file when serializing it.**
The question is: What do I need to do to make the "Enemy" object constructor run at the time of deserialization?
List:
public List< Ente > EnteList { get; set; } = new List< Ente >();
Code serialization and deserialization:
EnteList.Add( new Enemy( ) );
JsonSerializerSettings setting = new JsonSerializerSettings();
setting.TypeNameHandling = TypeNameHandling.Objects;
string json = JsonConvert.SerializeObject( EnteList, Formatting.Indented, setting );
EnteList.Clear();
EnteList = JsonConvert.DeserializeObject< List< Ente > >( json );
Class Ente and Enemy:
public class Ente
{
public Ente()
{
Console.WriteLine( "\n Constructor of Ente executed" );
}
}
public class Enemy : Ente
{
public Enemy()
{
Console.WriteLine( "\n Constructor of Enemy executed" );
}
}