1

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
Cihan Kurt
  • 343
  • 1
  • 5
  • 21
  • You could use a custom `JsonConverter` as described in [Json.Net Serialization of Type with Polymorphic Child Object](https://stackoverflow.com/q/29528648/3744182), [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538/3744182) and [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182). – dbc Jun 03 '21 at 12:29
  • Or you could use [`TypeNameHandling`](https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm) as described in [Json.net serialize/deserialize derived types?](https://stackoverflow.com/q/8513042/3744182) or [how to deserialize JSON into IEnumerable with Newtonsoft JSON.NET](https://stackoverflow.com/q/6348215/3744182) - but watch out for the security risks explained in [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954/3744182). – dbc Jun 03 '21 at 12:29

0 Answers0