using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
[JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
public TBase Data { get; set; }
public class MySerializationBinder : DefaultSerializationBinder
const string MyNamespace = "foo";
public override Type BindToType(string assemblyName, string typeName)
if (!typeName.StartsWith(MyNamespace, StringComparison.OrdinalIgnoreCase))
throw new JsonSerializationException($"Request type {typeName} not supported, please use an IFoo");
var type = base.BindToType(assemblyName, typeName);
public interface IFoo { }
public IList<string> Items { get; set; } = new List<string>();
public class Foo2: IFoo { }
public static void Test()
var settings = new JsonSerializerSettings
SerializationBinder = new MySerializationBinder(),
TypeNameHandling = TypeNameHandling.None,
var json = JsonConvert.SerializeObject(new Root<foo.IFoo> { Data = new foo.Foo1 { Items = { "Hello" } } }, settings);
var foo = JsonConvert.DeserializeObject<Root<foo.IFoo>>(json, settings)?.Data;
Assert.AreEqual(typeof(foo.Foo1), foo.GetType());
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];