[Fork] [Fork] [Fork] https://stackoverflow.com/questions/58074304/is-polymorphic-deserialization-possible-in-system-text-json/

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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/58074304/is-polymorphic-deserialization-possible-in-system-text-json/
public abstract class BaseType { } // Properties omitted

public class DerivedType1 : BaseType { public string Derived1 { get; set; } } 
public class DerivedType2 : BaseType { public int Derived2 { get; set; } }

public class DerivedType3 : BaseType { public string Derived3 { get; set; } } 

class TestClass
{
	public static void Test()
	{
		var list = new List<BaseType> { new DerivedType1 { Derived1 = "value 1" } };

		var resolver = new DefaultJsonTypeInfoResolver
		{
			Modifiers =
			{
				// Add an Action<JsonTypeInfo> modifier that sets up the polymorphism options for BaseType
				static typeInfo =>
				{
					if (typeInfo.Type != typeof(BaseType))
						return;
					typeInfo.PolymorphismOptions = new()
					{
						DerivedTypes =
						{
							new JsonDerivedType(typeof(DerivedType1), "Derived1"),
							new JsonDerivedType(typeof(DerivedType2), "Derived2")
						}
					};
				},
				// Add other modifiers as required.
			}
		};
		var options = new JsonSerializerOptions
		{
			TypeInfoResolver = resolver,
			// Add other options as required
		};			

		var json = JsonSerializer.Serialize(list, options);

		Console.WriteLine(json);

		Assert.That(json.Contains("value 1"));

		var list2 = JsonSerializer.Deserialize<List<BaseType>>(json, options);

		Assert.AreEqual(list2[0].GetType(), list[0].GetType());

		var json2 = JsonSerializer.Serialize(list2, options);

		Assert.AreEqual(json, json2);
	}	
}

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.Test();
		}
		catch (Exception ex)
		{
			Console.WriteLine("Failed with unhandled exception: ");
			Console.WriteLine(ex);
			throw;
		}
	}
}
;