json.net - Newtonsoft.Json 具有用于匿名类型的长 $type 字符串

标签 json.net

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/

相关文章:

javascript - NewtonSoft JSON 转换器序列化但执行起来很奇怪。怎么修?

c# - 使用 Json.NET 序列化/反序列化具有混合类型的数组

c# - 当我从 Json.net 反序列化对象时设置访问器不被调用

javascript - Newtonsoft Json.net 解析 bool 值时出错

c# - 如何将字符串序列化为 JSON 并按其中一个值进行分组?

c# - 如何在 json.net 中返回 json 对象而不是字符串?

.net - 反序列化空值JSON.net时抛出空值异常

Json.NET (Newtonsoft.Json) - 两个同名的 'properties'?

c# - 使用嵌入在字符串值中的子对象反序列化 JSON 字符串

c# - WebAPI 返回没有根节点的 JSON 数组