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;
public class CharacterData { }
public class DoNotShowMyTypeName { }
public class CharacterDataSerializationBinder : ISerializationBinder
readonly ISerializationBinder defaultBinder;
public CharacterDataSerializationBinder() : this(null) { }
public CharacterDataSerializationBinder(ISerializationBinder defaultBinder) { this.defaultBinder = defaultBinder; }
void ISerializationBinder.BindToName(Type serializedType, out string assemblyName, out string typeName)
switch (serializedType.Name)
assemblyName = "CharacterData";
typeName = serializedType.Name;
typeName = serializedType.Name;
typeName = serializedType.Name;
if (defaultBinder == null)
assemblyName = typeName = null;
defaultBinder.BindToName(serializedType, out assemblyName, out typeName);
Type ISerializationBinder.BindToType(string assemblyName, string typeName)
return typeof(CharacterData);
if (defaultBinder == null)
return defaultBinder.BindToType(assemblyName, typeName);
public static void Test()
Test(new DefaultSerializationBinder());
public static void Test(ISerializationBinder innerBinder)
Console.WriteLine("\nTesting innerBinder {0}:", innerBinder == null ? "null" : innerBinder.ToString());
var test = new List<object>
new DoNotShowMyTypeName(),
new Dictionary<string, object>
{ "one", new CharacterData() },
{ "two", new DoNotShowMyTypeName() },
new object [] { "hello", new CharacterData(), new DoNotShowMyTypeName() },
var settings = new JsonSerializerSettings
TypeNameHandling = TypeNameHandling.Auto,
SerializationBinder = new CharacterDataSerializationBinder(innerBinder)
var jsonData = JsonConvert.SerializeObject(test, Formatting.Indented, settings);
Console.WriteLine(jsonData);
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.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];