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?
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.
Try changing your serializer settings to include the following:
jsonSerializerSettings.TypeNameAssemblyFormat =
System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With