Csharp/C#教程:JSON.Net:在不指定程序集的情况下反序列化多态类型分享


JSON.Net:在不指定程序集的情况下反序列化多态类型

我看到使用JSON.Net,如果$type属性指定JSON对象的特定类型,我可以解码多态对象。 在我看到的所有示例中, $type包含命名空间。 是否可以使这个工作包括一个简单的类型名称而不需要汇编? 如果可能的话,我很乐意为JsonSerializer指定一个默认程序集。

我可以使用以下命令反序列化JSON:

 public class SingleAssemblyJsonTypeBinder : SerializationBinder { private readonly Assembly _assembly; private Dictionary _typesBySimpleName = new Dictionary(StringComparer.OrdinalIgnoreCase); private Dictionary _simpleNameByType = new Dictionary(); public SingleAssemblyJsonTypeBinder(Assembly assembly) { _assembly = assembly; _typesBySimpleName = new Dictionary(); foreach (var type in _assembly.GetTypes().Where(t => t.IsPublic)) { if (_typesBySimpleName.ContainsKey(type.Name)) throw new InvalidOperationException("Cannot user PolymorphicBinder on a namespace where multiple public types have same name."); _typesBySimpleName[type.Name] = type; _simpleNameByType[type] = type.Name; } } public override Type BindToType(string assemblyName, string typeName) { Type result; if (_typesBySimpleName.TryGetValue(typeName.Trim(), out result)) return result; return null; } public override void BindToName(Type serializedType, out string assemblyName, out string typeName) { string name; if (_simpleNameByType.TryGetValue(serializedType, out name)) { typeName = name; assemblyName = null;// _assembly.FullName; } else { typeName = null; assemblyName = null; } } } 

 public static JsonSerializerSettings GetJsonSerializationSettings() { var settings = new JsonSerializerSettings(); settings.Binder = new SingleAssemblyJsonTypeBinder(typeof(MvcApplication).Assembly); settings.TypeNameHandling = TypeNameHandling.Objects; return settings; } 

 var serializer = JsonSerializer.Create(settings); 

但是我无法使用MVC来完成这项工作。 我正在按照Application_Start下面的代码配置JSON反序列化,并且对象被反序列化,但使用基类型1。

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Binder = new SingleAssemblyJsonTypeBinder(this.GetType().Assembly); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.All; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple; 

创建派生的SerializationBinder ,其中覆盖BindToName并将out string assemblyName设置为null( 编辑 :或您的默认程序集名称),并out string typeName为您的条带类型名称

在序列化之前将活页夹设置为JsonSerializerSettings.Binder

如果这不起作用,请告诉我

上述就是C#学习教程:JSON.Net:在不指定程序集的情况下反序列化多态类型分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/988936.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐