How to omit assembly name from type name when serializing and deserializing in JSON.Net?

We have a single contract assembly in which there are all our data contracts. We use JSON.net to serialize our data contracts for json.

JSON.Net adds the type name and assembly name in the $ type attribute during serialization. Since all our data contracts are in the same assembly, which is always loaded in the current application domain, we can omit this.

How can we achieve this?

thanks

+4
source share
2 answers

You can use the Binder property in 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 your own class from the SerializationBinder and override two methods:

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

The logic that you place in these methods will give you direct control over how type names are converted to a string representation in the $type field and how types are located at the time the given values ​​from $type executed.

In your case, if you want to omit the name of the Assembly, 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); } 
+5
source

I think it is possible to tag a class using JsonObjectAttribute

 [DataContract] [JsonObject("")] public class MyContractClass { ... } 

This should override the fact that it is also a DataContract.

0
source

Source: https://habr.com/ru/post/1380028/


All Articles