Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I omit the assembly name from the type name while serializing and deserializing in JSON.Net?

Tags:

json

json.net

We have a single contract assembly which has all our data contracts. We are using JSON.net for serializing our data contracts to json.

JSON.Net adds both the type name and the assembly name in the $type attribute on serialization. Since all our data contracts are in the same assembly which is always loaded in the current app domain, we should be able to omit this.

How can we achieve this?

Thanks

like image 600
SharePoint Newbie Avatar asked Nov 07 '11 17:11

SharePoint Newbie


1 Answers

You can use the Binder property in your JsonSerializerSettings.

This blog post (by the library author) describes the steps: http://james.newtonking.com/archive/2011/11/19/json-net-4-0-release-4-bug-fixes.aspx

In short, you create a custom class deriving from SerializationBinder and override two methods:

  • BindToName(Type serializedType, out string assemblyName, out string typeName)
  • BindToType(string assemblyName, string typeName)

The logic you place in those methods will give you direct control over how type names are converted to string representation in the $type field, and how types are located at run-time given values from $type.

In your case, wanting to omit the Assembly name, you can probably do:

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

public override Type BindToType(string assemblyName, string typeName)
{
    return Type.GetType(typeName);
}
like image 139
DuckMaestro Avatar answered Oct 16 '22 02:10

DuckMaestro