Json.NET TypeNameHandling和TypeNameAssemblyFormatHandling

时间:2018-12-03 22:01:59

标签: c# json serialization json.net

希望您能帮助我了解Json.NET中的TypeNameHandlingTypeNameAssemblyFormatHandling设置如何工作。

场景

假设具有以下实体:

namespace SerDesTest
{
    public abstract class BaseClass
    {
        public int Int0 { get; set; }
        public string String0 { get; set; }
    }

    public class Father : BaseClass
    {
        public Father() { Children = new List<BaseClass>(); }

        public List<BaseClass> Children { get; set; }
    }

    public class Child : BaseClass
    {
        public Child(Father father) { Father = father; }

        public Father Father { get; set; }
        public int Int1 { get; set; }
        public string String1 { get; set; }
    }

    public class Generic<T>
    {
        public int GenericInt { get; set; }
        public string GenericString { get; set; }
        public T GenericProperty { get; set; }
    }
}

并使用以下辅助方法:

public static class JsonHelper
{
    public static string Serialize(object obj)
    {
        return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects,
            TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            SerializationBinder = new JsonManagerKnownTypesBinder()
            {
                KnownTypes = GetTypeList("SerDesTest")
            }
        });
    }

    public static TEntity Deserialize<TEntity>(string json)
    {
        return JsonConvert.DeserializeObject<TEntity>(json, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects,
            TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            SerializationBinder = new JsonManagerKnownTypesBinder()
            {
                KnownTypes = GetTypeList("SerDesTest")
            }
        });
    }

    public static IList<Type> GetTypeList(string assemblyName)
    {
        List<Type> list = new List<Type>();
        Assembly assembly = Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), $"{assemblyName}.dll"));

        if (assembly != null)
        {
            list.AddRange(assembly.GetTypes());
        }
        return list.AsParallel().Distinct().ToList<Type>();
    }
}

要运行以下命令:

internal static class Program
{
    private static void Main(string[] args)
    {
        try
        {
            Father father = new Father();
            Generic<Child> generic = new Generic<Child>
            {
                GenericInt = 100,
                GenericString = "100",
                GenericProperty = new Child(father)
                {
                    Int0 = 0,
                    Int1 = 1,
                    String0 = "0",
                    String1 = "1"
                }
            };

            string genericJson = JsonHelper.Serialize(generic);

            Console.WriteLine(genericJson);

            Generic<Child> genericDes = JsonHelper.Deserialize<Generic<Child>>(genericJson);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.ReadKey();
    }
}

运行测试程序

运行测试程序时,我获得以下json:

{
  "$type": "Generic`1",
  "GenericInt": 100,
  "GenericString": "100",
  "GenericProperty": {
    "$type": "Child",
    "Father": {
      "$type": "Father",
      "Children": [],
      "Int0": 0,
      "String0": null
    },
    "Int1": 1,
    "String1": "1",
    "Int0": 0,
    "String0": "0"
  }
}

和以下异常:

  

在JSON'SerDesTest.Generic 1, SerDesTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with 'SerDesTest.Generic 1 [[[SerDesTest.Child,SerDesTest,   版本= 1.0.0.0,文化=中性,公钥令牌=空]],SerDesTest,   版本= 1.0.0.0,文化=中性,PublicKeyToken =空”。路径“ $ type”,   第2行,位置22。

问题

我有两个问题/问题:

1)由于Json.NET配置,我期望json第2行中的$type字段具有“全限定名”,例如:“ $ type”:“ SerDesTest.Generic [SerDesTest,CHild]“ ,而不仅是” $ type“:” Generic`1“ ...

2)您是否有解决异常的想法?

谢谢你, Attilio

更新1

根据Brian Rogers的要求,遵循JsonManagerKnownTypesBinder的代码:

public class JsonManagerKnownTypesBinder : ISerializationBinder
{
    public IList<Type> KnownTypes { get; set; }

    public Type BindToType(string assemblyName, string typeName)
    {
        return KnownTypes.SingleOrDefault(t => t.Name == typeName);
    }

    public void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
        assemblyName = null;
        typeName = serializedType.Name;
    }
}

更新2

更多测试。如果我未设置SerializationBinder,则使用以下版本的JsonHelper类:

public static class JsonHelper
{
    public static string Serialize(object obj)
    {
        return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All,
            TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            //SerializationBinder = new JsonManagerKnownTypesBinder()
            //{
            //    KnownTypes = GetTypeList("SerDesTest")
            //}
        });
    }

    public static TEntity Deserialize<TEntity>(string json)
    {
        return JsonConvert.DeserializeObject<TEntity>(json, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All,
            TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            //SerializationBinder = new JsonManagerKnownTypesBinder()
            //{
            //    KnownTypes = GetTypeList("SerDesTest")
            //}
        });
    }
}

我解决了所有问题:首先,我在反序列化过程中没有例外;第二,我将以下json作为输出:

{
  "$type": "SerDesTest.Generic`1[[SerDesTest.Child, SerDesTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], SerDesTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
  "GenericInt": 100,
  "GenericString": "100",
  "GenericProperty": {
    "$type": "SerDesTest.Child, SerDesTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
    "Father": {
      "$type": "SerDesTest.Father, SerDesTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
      "Children": {
        "$type": "System.Collections.Generic.List`1[[SerDesTest.BaseClass, SerDesTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
        "$values": []
      },
      "Int0": 0,
      "String0": null
    },
    "Int1": 1,
    "String1": "1",
    "Int0": 0,
    "String0": "0"
  }
}

您可以使用TypeNameAssemblyFormatHandling选项来调整$Type字段中包含的信息。

问题就变成了:如何实现ISerializationBinder接口以获取更安全的软件?

1 个答案:

答案 0 :(得分:0)

要在$ type字段中使用“全限定名”,请在更新1 中更改const TextDetailScreen = (props) => { return ( <ScrollView> <Text> ...longText...</Text> </ScrollView> ); }; ,以在JsonManagerKnownTypesBinder和{{1}中设置程序集名称。 }方法,如下所示

BindToType