当Json.Net
typenamehandling
设置为Object时,匿名对象可以包含很长的类型名称,例如:
_IB_8bgoVaqDaVjOpT0PxYDBjiO_pwOo[[System.Guid, mscorlib],[System.Nullable`1[[System.Guid, mscorlib]], mscorlib],[System.String, mscorlib],[System.String, mscorlib],[System.String, mscorlib],[System.String, mscorlib],[System.String, mscorlib],[System.String, mscorlib],[System.Nullable`1[[System.Int32, mscorlib]], mscorlib],[System.Nullable`1[[System.Int32, mscorlib]], mscorlib],[System.Nullable`1[[System.Int32, mscorlib]], mscorlib],[System.String, mscorlib]], _IB_8bgoVaqDaVjOpT0PxYDBjiO_pwOo_IdeaBlade
我可以通过调整来减小这个尺寸吗?
答案 0 :(得分:2)
创建自己的SerializationBinder,派生自DefaultSerializationBinder。
使用您自己的匿名类型逻辑覆盖BindToName(下面的默认代码)(默认实现如下):
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
#if NETFX_CORE || PORTABLE
assemblyName = serializedType.GetTypeInfo().Assembly.FullName;
typeName = serializedType.FullName;
#else
assemblyName = serializedType.Assembly.FullName;
typeName = serializedType.FullName;
#endif
}
然后,在调用Serialize或Deserialize之前,将JsonSerializer的Binder属性设置为自定义SerializationBinder的实例。
您的实施可能类似于:
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
//http://stackoverflow.com/questions/2483023/how-to-test-if-a-type-is-anonymous
if(Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic)
{
return "AnonymousType";
}
base.BindToName(serializedType, out assemblyName, out typeName);
}