Let's say I have these classes:
public class MachineResult
{
public string Id {get; set;}
public List<Base> Results {get; set;}
}
public class Base
{
public string Name {get; set;}
}
public class Derived<T> : Base
{
public T Value {get; set;}
}
And I am doing the following:
MachineResult machineResult = new MachineResult
{
Id = "x",
Results = new List<Base>()
};
var temp = new Derived<int>
{
Name = "y",
Value = 5
};
machineResult.Results.Add(temp);
I can easily serialize these with Newtonsoft's Json serializer. DOT Net3.1's System.Text.Json serializer can not serialize with the Generic Derived class. That's why I chose Newtonsoft instead of System.Text.Json.
However, when I want to deserialize the Json string into a MachineResult, I get a list full with base classes instead of the derived generic classes. I do understand that the serializer can not know which type is inside that string and make the right derived class for it.
However, I want to be able to deserialize a valid jsonString into the object: MachineResult, containing a list of derived generic classes. I've tried the basic thing:
MachineResult deserializedResult = JsonConvert.DeserializeObject<MachineResult>(jsonString);
It results in a MachineResult object with just a list of Base classes. The base classes contain only a name property. I want the generic value type aswell.