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

耗尽温柔 提交于 2019-12-23 18:44:51

问题


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?


回答1:


Try changing your serializer settings to include the following:

jsonSerializerSettings.TypeNameAssemblyFormat =
    System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full;



回答2:


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.



来源:https://stackoverflow.com/questions/24807110/json-net-how-to-deserialize-a-type-in-a-dynamically-loaded-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!