EDIT see #30083 (comment) for a finalized proposal.
Original proposal by @Symbai (click to view)
public class FooBase
public class FooA : FooBase
public class FooB : FooBase
List<FooBase> SerializationObject = new List<FooBase> { new FooA(), new FooB() }
Serialized with Newtonsoft.JSON
JsonSerializerSettings Settings = new JsonSerializerSettings
{
SerializationBinder = new KnownTypesBinder
{
KnownTypes = new List<Type> { typeof(FooA), typeof(FooB) }
},
TypeNameHandling = TypeNameHandling.Objects
};
List<FooBase> FooBases = new List<FooBase>() { new FooA(), new FooB() };
var json = JsonConvert.SerializeObject(FooBases, Settings);
will be:
[{"$type":"FooA","NameA":"FooA","Name":"FooBase"},{"$type":"FooB","NameB":"FooB","Name":"FooBase"}]
When using System.Text.Json.JsonSerializer to deserialize the json, FooA and FooB are both type of FooBase. Is there a way that JsonSerializer supports inheirited classes? How can I make sure the type will be the same and not the base class it inherits from?