using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using System.Collections.Generic;
[JsonConverter(typeof(MyJsonConverter))]
public abstract class A {
public string Id { get; set; }
public string F { get; set; }
public string G { get; set; }
public List<A> Items { get; set; }
public class MyJsonConverter : JsonConverter<A>
public override bool CanConvert(Type type)
return type.IsAssignableFrom(typeof(A));
public override A Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
Console.WriteLine("Read Json");
if (JsonDocument.TryParseValue(ref reader, out var doc))
if (doc.RootElement.TryGetProperty("type", out var type))
var typeValue = type.GetInt16();
var rootElement = doc.RootElement.GetRawText();
return JsonSerializer.Deserialize<B>(rootElement, options);
} else if (typeValue == 1) {
return JsonSerializer.Deserialize<C>(rootElement, options);
throw new JsonException("{typeValue} has not been mapped to a custom type yet!");
throw new JsonException("Failed to extract type property, it might be missing?");
throw new JsonException("Failed to parse JsonDocument");
public override void Write(Utf8JsonWriter writer, A value, JsonSerializerOptions options)
throw new NotImplementedException();
public static void Main()
var result = JsonSerializer.Deserialize<MyJson>(json);
Console.WriteLine(result.Items.First().Id);