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 CustomerInformation
public int? YearsofPurchase { get; set; }
public int? Age{ get; set; }
public static void Test()
var binder = new KnownTypesBinder(new Dictionary<string, Type>{ {"Customer.CustomerInformation", typeof(Common.CustomerInformation) }});
Func<JsonSerializerSettings> custDefualtSettings = () => new JsonSerializerSettings
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
MissingMemberHandling = MissingMemberHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Include,
SerializationBinder = binder,
Console.WriteLine(JsonConvert.SerializeObject(new Common.CustomerInformation(), custDefualtSettings()));
var response = GetJson();
var result = JsonConvert.DeserializeObject<Common.CustomerInformation>(response, custDefualtSettings());
Assert.AreEqual(null, result.Age);
Assert.AreEqual(null, result.YearsofPurchase);
""$type"": ""Customer.CustomerInformation, Customer.Common"",
""CustomerId"": 103606055,
""YearsofPurchase "": null,
public class KnownTypesBinder : ISerializationBinder
readonly Dictionary<string, Type> nameToType;
readonly Dictionary<Type, string> typeToName;
public KnownTypesBinder(IEnumerable<KeyValuePair<string, Type>> nameToType)
this.nameToType = nameToType.ToDictionary(p => p.Key, p => p.Value);
this.typeToName = nameToType.ToDictionary(p => p.Value, p => p.Key);
public Type BindToType(string assemblyName, string typeName)
if(nameToType.TryGetValue(typeName, out var type))
throw new JsonSerializationException(string.Format("Unknown type name {0} ({1})", typeName, assemblyName));
public void BindToName(Type serializedType, out string assemblyName, out string typeName)
if (!typeToName.TryGetValue(serializedType, out typeName))
throw new JsonSerializationException(string.Format("Unknown type {0}", serializedType));
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];