当 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
我可以调整任何设置来减小该大小吗?
最佳答案
创建您自己的从 DefaultSerializationBinder 派生的 SerializationBinder。
使用您自己的匿名类型逻辑覆盖 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);
}
关于json.net - Newtonsoft.Json 具有用于匿名类型的长 $type 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28510219/