我看到使用JSON.Net,如果$type
属性指定JSON对象的特定类型,我可以解码多态对象。在我看到的所有示例中,$type
包含命名空间。是否可以使这项工作包括一个简单的类型名称而不需要汇编?如果可能的话,我很乐意为JsonSerializer指定默认程序集。
我可以使用以下命令反序列化JSON:
public class SingleAssemblyJsonTypeBinder : SerializationBinder
{
private readonly Assembly _assembly;
private Dictionary<string, Type> _typesBySimpleName = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
private Dictionary<Type,string> _simpleNameByType = new Dictionary<Type, string>();
public SingleAssemblyJsonTypeBinder(Assembly assembly)
{
_assembly = assembly;
_typesBySimpleName = new Dictionary<string, Type>();
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反序列化,并且对象被反序列化,但使用基类型。
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;
答案 0 :(得分:9)
创建派生SerializationBinder
,其中覆盖BindToName
并将out string assemblyName
设置为null(修改:或您的默认程序集名称)和out string typeName
到你的条纹类型名称
在序列化之前将活页夹设置为JsonSerializerSettings.Binder
。
如果这不起作用,请告诉我