我发现,使用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;
创建一个派生的SerializationBinder
,其中重写BindToName
并将out string assemblyName
设置为null(编辑:或默认程序集名称),并将out string typeName
设置为条带类型名称
在序列化之前,将活页夹设置为JsonSerializerSettings.Binder
。
如果不起作用,请告诉我