Click or drag to resize
Json.NETCustom SerializationBinder
 

This sample creates a custom SerializationBinder that writes only the type name when including type data in JSON.

Sample
Types
 1public class KnownTypesBinder : ISerializationBinder
 2{
 3    public IList<Type> KnownTypes { get; set; }
 4
 5    public Type BindToType(string assemblyName, string typeName)
 6    {
 7        return KnownTypes.SingleOrDefault(t => t.Name == typeName);
 8    }
 9
10    public void BindToName(Type serializedType, out string assemblyName, out string typeName)
11    {
12        assemblyName = null;
13        typeName = serializedType.Name;
14    }
15}
16
17public class Car
18{
19    public string Maker { get; set; }
20    public string Model { get; set; }
21}
Usage
 1KnownTypesBinder knownTypesBinder = new KnownTypesBinder
 2{
 3    KnownTypes = new List<Type> { typeof(Car) }
 4};
 5
 6Car car = new Car
 7{
 8    Maker = "Ford",
 9    Model = "Explorer"
10};
11
12string json = JsonConvert.SerializeObject(car, Formatting.Indented, new JsonSerializerSettings
13{
14    TypeNameHandling = TypeNameHandling.Objects,
15    SerializationBinder = knownTypesBinder
16});
17
18Console.WriteLine(json);
19// {
20//   "$type": "Car",
21//   "Maker": "Ford",
22//   "Model": "Explorer"
23// }
24
25object newValue = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
26{
27    TypeNameHandling = TypeNameHandling.Objects,
28    SerializationBinder = knownTypesBinder
29});
30
31Console.WriteLine(newValue.GetType().Name);
32// Car