[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 NUnit.Framework; // Throws NUnit.Framework.AssertionException

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

[JsonDerivedType(typeof(DerivedType1), "DerivedType1")]
[JsonDerivedType(typeof(DerivedType2), "DerivedType2")]
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 json = JsonSerializer.Serialize(list);

		Console.WriteLine(json);

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

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

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

		var json2 = JsonSerializer.Serialize(list2);

		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;
		}
	}
}
;