Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.net: how to deserialize a type in a dynamically loaded assembly?

Tags:

json.net

I'm dynamically loading an assembly using Assembly.LoadFrom(), then instantiating some of its types using .CreateInstance(). Next, I put these objects into an array and serialize it to a file using json.net (configured with TypeNameHandling.Auto). In the file I can see that it is storing the correct type names, e.g.:-

"Features": [{
    "$type": "FeaturesAssembly.SomeFeature, FeaturesAssembly",
    // Other serialized properties
}]

The problem is that I can't deserialize the file. Json.net throws a JsonSerializationException, message "Could not load assembly 'FeatureAssembly'", despite the necessary assembly having been dynamically loaded first. What am I missing?

like image 880
Andrew Stephens Avatar asked Jan 10 '23 05:01

Andrew Stephens


2 Answers

This looks to me like it might be a bug/limitation in Json.NET.

Digging into the source for DefaultSerializationBinder.GetTypeFromTypeNameKey() (viewable e.g. here), the binder first tries to load the desired assembly by partial name from the app directory and GAC. If that fails, it compares the desired assembly name against the fully-qualified names of all assemblies loaded in the current app domain.

This last step will never find a match when the JSON document contains only the simple assembly name (the default), even if the required assembly has already been loaded in the current app domain.

One possible fix would be for the binder to compare the desired assembly name against each assembly's fully-qualified and simple names.

like image 182
Matt Craig Avatar answered May 04 '23 19:05

Matt Craig


Try changing your serializer settings to include the following:

jsonSerializerSettings.TypeNameAssemblyFormat =
    System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full;
like image 35
Brian Rogers Avatar answered May 04 '23 20:05

Brian Rogers