Skip to content

Latest commit

 

History

History
68 lines (57 loc) · 2.08 KB

File metadata and controls

68 lines (57 loc) · 2.08 KB

Custom SerializationBinder

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

public class KnownTypesBinder : ISerializationBinder
{
    public IList<Type> KnownTypes { get; set; }

    public Type BindToType(string assemblyName, string typeName) =>
        KnownTypes.SingleOrDefault(t => t.Name == typeName);

    public void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
        assemblyName = null;
        typeName = serializedType.Name;
    }
}

public class Car
{
    public string Maker { get; set; }
    public string Model { get; set; }
}

snippet source | anchor

var knownTypesBinder = new KnownTypesBinder
{
    KnownTypes = [typeof(Car)]
};

var car = new Car
{
    Maker = "Ford",
    Model = "Explorer"
};

var json = JsonConvert.SerializeObject(car, Formatting.Indented, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Objects,
    SerializationBinder = knownTypesBinder
});

Console.WriteLine(json);
// {
//   "$type": "Car",
//   "Maker": "Ford",
//   "Model": "Explorer"
// }

var newValue = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Objects,
    SerializationBinder = knownTypesBinder
});

Console.WriteLine(newValue.GetType().Name);
// Car

snippet source | anchor