CSharp · Console
using System;
using System.Linq;
using System.Data;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/77809445/custom-typeinforesolver-to-manage-polimorphic-deserialization-in-system-text-jso
#nullable enable
public static class JsonExtensions
{
public static void AddNativePolymorphicTypInfo(JsonTypeInfo jsonTypeInfo)
{
if (typeof(ValueObject).IsAssignableFrom(jsonTypeInfo.Type) && !jsonTypeInfo.Type.IsSealed) {
jsonTypeInfo.PolymorphismOptions = new JsonPolymorphismOptions {
TypeDiscriminatorPropertyName = "$mytype",
IgnoreUnrecognizedTypeDiscriminators = true,
UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization,
};
// This query is likely to be slow so you might want to cache all types assignable to typeof(ValueObject) in a lazy static singleton
var types = Assembly
.GetExecutingAssembly()
.GetTypes()
.Where(t => !t.IsAbstract && jsonTypeInfo.Type.IsAssignableFrom(t));
foreach (var t in types.Select(t => new JsonDerivedType(t, t.Name.ToLowerInvariant()))) // Fixed ToLower() => ToLowerInvariant
jsonTypeInfo.PolymorphismOptions.DerivedTypes.Add(t);
}
}
}
public class MyBaseClass;
public class ValueObject;
public class MyValueObject : ValueObject {
public int Counter { get; set; }
}
public class MySubValueObject : MyValueObject {
}
public class RootObjectOne {
public ValueObject? ValueObject { get; set; }
}
public class RootObjectTwo {
public MyValueObject? ValueObject { get; set; }
}
class TestClass {
private static JsonSerializerOptions BuildSerializerOptions() {
return new JsonSerializerOptions {
TypeInfoResolver = new DefaultJsonTypeInfoResolver()
.WithAddedModifier(JsonExtensions.AddNativePolymorphicTypInfo),
// Add other options as required, e.g.
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
}
public static void Test1_Serialize_Only_MyValueObject_Declared_AsSelf() {
Console.WriteLine("TEST 1");
MyValueObject rootObject = new MyValueObject() { Counter = 5 };
var json = JsonSerializer.Serialize(rootObject, BuildSerializerOptions());
Console.WriteLine(json);
var expectedJson = "{\"$mytype\":\"myvalueobject\",\"counter\":5}";
Assert.That(expectedJson == json);
}
public static void Test2_Serialize_Only_MyValueObject_Declared_AsBase() {
Console.WriteLine("TEST 2");
ValueObject rootObject = new MyValueObject() { Counter = 5 };
var json = JsonSerializer.Serialize(rootObject, BuildSerializerOptions());
Console.WriteLine(json);
var expectedJson = "{\"$mytype\":\"myvalueobject\",\"counter\":5}";
Assert.That(expectedJson == json);
}
public static void Test3_Serialize_RootObjectOne_With_ValueObject_Declared_AsBase() {
Console.WriteLine("TEST 3");
var rootObject = new RootObjectOne { ValueObject = new MyValueObject() { Counter = 5 } };
var json = JsonSerializer.Serialize(rootObject, BuildSerializerOptions());
Console.WriteLine(json);
var expectedJson = "{\"valueObject\":{\"$mytype\":\"myvalueobject\",\"counter\":5}}";
Assert.That(expectedJson == json);
}
public static void Test4_Serialize_RootObjectTwo_With_ValueObject_Declared_AsSelf() {
Console.WriteLine("TEST 4");
var rootObject = new RootObjectTwo { ValueObject = new MyValueObject() { Counter = 5 } };
var json = JsonSerializer.Serialize(rootObject, BuildSerializerOptions());
Console.WriteLine(json);
var expectedJson = "{\"valueObject\":{\"$mytype\":\"myvalueobject\",\"counter\":5}}";
Assert.That(expectedJson == json);
}
public static void Test5_Serialize_MySubValueObject() {
Console.WriteLine("TEST 5");
var rootObject = new MySubValueObject { Counter = 5 };
var json = JsonSerializer.Serialize(rootObject, BuildSerializerOptions());
Console.WriteLine(json);
var expectedJson = "{\"$mytype\":\"mysubvalueobject\",\"counter\":5}";
Assert.That(expectedJson == json);
}
}
public class Program
{
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();
try {
TestClass.Test1_Serialize_Only_MyValueObject_Declared_AsSelf();
}
catch (Exception ex) {
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
}
try {
TestClass.Test2_Serialize_Only_MyValueObject_Declared_AsBase();
}
catch (Exception ex) {
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
}
try {
TestClass.Test3_Serialize_RootObjectOne_With_ValueObject_Declared_AsBase();
}
catch (Exception ex) {
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
}
try {
TestClass.Test4_Serialize_RootObjectTwo_With_ValueObject_Declared_AsSelf();
}
catch (Exception ex) {
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
}
try
{
TestClass.Test5_Serialize_MySubValueObject();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
}
}
}