CSharp · Console
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))]
[JsonDerivedType(typeof(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 DerivedType3 { Derived3 = "value 3" } };
var json = JsonSerializer.Serialize(list);
Console.WriteLine(json);
Assert.That(json.Contains("value 3"));
}
}
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;
}
}
}