using System.Collections;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Nodes;
public abstract class ClassC
public string PropertyC { get; set; }
public string TypeDiscriminator => this.GetType().FullName;
public class ClassB : ClassC
public string PropertyB { get; set; }
public class ClassA : ClassB
public string PropertyA { get; set; }
public class ClassCJsonConverter : JsonConverter<ClassC>
public override bool CanConvert(Type typeToConvert) => typeToConvert.IsAssignableFrom(typeof(ClassC)) && typeToConvert.IsAbstract;
public override ClassC? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
using (var jsonDoc = JsonDocument.ParseValue(ref reader))
var root = jsonDoc.RootElement;
var typeDiscriminator = root.GetProperty("TypeDiscriminator").GetString();
var type = typeDiscriminator == null ? null : Type.GetType(typeDiscriminator);
if (type == null || CanConvert(type))
throw new JsonException($"Type {typeDiscriminator} could not be found or is invalid.");
return (ClassC?)root.Deserialize(type, options);
public override void Write(Utf8JsonWriter writer, ClassC value, JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, value, value.GetType(), options);
public static void Test()
var options = new JsonSerializerOptions
Converters = { new ClassCJsonConverter() },
ClassA classA = new ClassA { PropertyA = "ValueA", PropertyB = "ValueB", PropertyC = "ValueC" };
string json = JsonSerializer.Serialize<ClassC>(classA, options);
ClassC deserialized = JsonSerializer.Deserialize<ClassC>(json, options)!;
Console.WriteLine(deserialized is ClassA);
public static void Main()
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");