[Fork] https://stackoverflow.com/questions/77848655/determine-if-type-isnt-recognized-in-system-text-json-serialization

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;

using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Nodes;

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

#nullable enable

public static partial class JsonExtensions
{
	public static Action<JsonTypeInfo> SetupUnknownDerivedTypeHandling(bool objectsOnly = false) =>
		(typeInfo) =>
	{
		// Polymorphism using type discriminators is only supported for type hierarchies that use the default converters for objects, collections, and dictionary types.
		if (typeInfo.Kind == JsonTypeInfoKind.None || typeInfo.Type.IsSealed || typeInfo.Type == typeof(object))
			return;
		if (objectsOnly && typeInfo.Kind != JsonTypeInfoKind.Object)
			return;
		// TODO: decide whether to fail serialization even for types marked with
		// [JsonPolymorphic(UnknownDerivedTypeHandling = FallBackToBaseType or FallBackToNearestAncestor)]
		if (typeInfo.PolymorphismOptions == null)
		{
			typeInfo.PolymorphismOptions = new() { DerivedTypes = { new(typeInfo.Type) } };
			// TODO: decide whether to fail serialization even for types marked with
			// [JsonPolymorphic(UnknownDerivedTypeHandling = FallBackToBaseType or FallBackToNearestAncestor)]
			// If so, move the setting of UnknownDerivedTypeHandling out of this if statement.
			typeInfo.PolymorphismOptions.UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization;
		};
	};
}

public class Root<T>
{
	public T? Data { get; set; }
}

public class Foo;
public class SubFoo : Foo;
public class SubSubFoo : SubFoo;

public class FooList : List<Foo>;
public class SpecialFooList : FooList;

public class FooDictionary : Dictionary<string, Foo>;
public class SpecialFooDictionary : FooDictionary;

    class TestClass
    {
        public static void Test()
        {
			Assert.DoesNotThrow(() => Serialize<Foo, Foo>(false));
			Assert.DoesNotThrow(() => Serialize<Foo, Foo>(true));
			Assert.Throws(Is.InstanceOf(typeof(Exception)), () => Serialize<Foo, SubFoo>(false));
			Assert.Throws(Is.InstanceOf(typeof(Exception)), () => Serialize<Foo, SubFoo>(true));

			Assert.DoesNotThrow(() => Serialize<FooList, FooList>(false));
			Assert.DoesNotThrow(() => Serialize<FooList, FooList>(true));
			Assert.Throws(Is.InstanceOf(typeof(Exception)), () => Serialize<FooList, SpecialFooList>(false));
			Assert.DoesNotThrow(() => Serialize<FooList, SpecialFooList>(true));

			Assert.DoesNotThrow(() => Serialize<FooDictionary, FooDictionary>(false));
			Assert.DoesNotThrow(() => Serialize<FooDictionary, FooDictionary>(true));
			Assert.Throws(Is.InstanceOf(typeof(Exception)), () => Serialize<FooDictionary, SpecialFooDictionary>(false));
			Assert.DoesNotThrow(() => Serialize<FooDictionary, SpecialFooDictionary>(true));

			Assert.DoesNotThrow(() => Serialize<object, int>(false));
		}	
		
		static void Serialize<TBase, TDerived>(bool objectsOnly) where TDerived : TBase, new()
		{
			var options = new JsonSerializerOptions()
			{
				// Configure either a DefaultJsonTypeInfoResolver or some JsonSerializerContext and add the required modifier:
				TypeInfoResolver = new DefaultJsonTypeInfoResolver() 
					.WithAddedModifier(JsonExtensions.SetupUnknownDerivedTypeHandling(objectsOnly)),
				// Set other options as required.
			};
			
			var json = JsonSerializer.Serialize<TBase>(new TDerived(), options);
			
			Console.WriteLine(json);
		}
	}

	public static class ObjectExtensions
	{
		public static T ThrowOnNull<T>(this T? value) where T : class => value ?? throw new ArgumentNullException();
	}

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