Newtonsoft.json序列化和反序列化base / inheirited类来自共享项目

时间:2017-08-28 16:07:39

标签: c# json serialization json.net shared-project

所以我有两个类,如下所示。它们都在同一个命名空间和同一个共享项目中。

public class Person{
   public string Name{get;set;}
}

public class EmployedPerson : Person{
   public string JobTitle{get;set;}
}

当我将这些项目串联到rabbitmq时,我将序列化为基类,如下所示:

JsonSerializerSettings settings = new JsonSerializerSettings
{
   TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
   TypeNameHandling = TypeNameHandling.Objects
};
JsonConvert.SerializeObject(input, settings)

然而,当反序​​列化时,我遇到了问题。我希望能够执行如下所示的操作,我将反序列化为基类,然后检查它是否是一个非常类型。

类型检查:

Person person = Deserialize<Person>(e.Body, Encoding.Unicode);
   if (person is EmployedPerson)
   {
    logger.LogInformation("This person has a job!");
    }

反序列化设置:

   JsonSerializerSettings settings = new JsonSerializerSettings
   {
      TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
      TypeNameHandling = TypeNameHandling.Auto
   };

反序列化逻辑:

    private static T Deserialize<T>(byte[] data, Encoding encoding) where T : class
    {
        try
        {
            using (MemoryStream stream = new MemoryStream(data))
            using (StreamReader reader = new StreamReader(stream, encoding))
                return JsonSerializer.Create(settings).Deserialize(reader, typeof(T)) as T;
        }
        catch (Exception e)
        {
            Type typeParameter = typeof(T);
            logger.LogError(LogEvent.SERIALIZATION_ERROR, e, "Deserializing type {@TypeName} failed", typeParameter.Name);
            logger.LogInformation(Encoding.UTF8.GetString(data));
            return default(T);
        }
    }

结果: 上面的代码失败,因为$ type属性包含程序集名称,并且在rabbitmq的每一端,程序集名称都不同,因为这些类在共享项目中。

示例错误:

Newtonsoft.Json.JsonSerializationException: Error resolving type specified in JSON 'Shared.Objects.EmployedPerson, Person.Dispatcher'. Path '$type', line 1, position 75. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Person.Dispatcher, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

1 个答案:

答案 0 :(得分:3)

谢谢@dbc,就我所知,你写一个自定义SerializationBinder的建议是我问题的最佳解决方案。

我在以下地址使用了KnownTypesBinder:https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm

KnownTypesBinder:

public class KnownTypesBinder : 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;
        }
    }

在序列化和反序列化端点上使用了将SerializationBinder设置为KnownTypesBinder实例的JsonSerializerSettings。我可能只需要它用于反序列化结束,但为了保持一致性而将它放在两者中。

settings = new JsonSerializerSettings
{
    TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
    TypeNameHandling = TypeNameHandling.Objects,
    SerializationBinder = new KnownTypesBinder()
};

创建设置对象后,我将其传递给JsonConvert序列化函数。

JsonConvert.DeserializeObject<T>(Encoding.Unicode.GetString(input), settings) 

另请注意,KnownTypesBinder中的KnownTypes必须预先填充您要反序列化的所有非基本类型。

修改 我目前不接受我自己的回答,因为我不知道如何处理复杂类型列表。例如,如果一个Person有一个List和一个List,当typeName为&#34; List`1&#34;时,你会返回什么类型?它可以是一个。

修改 以下版本的KnownTypesBinder解决了与对象列表相关的问题。

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

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

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