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



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

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.

@dbc谢谢你,据我所知,您编写自定义序列化绑定器的建议是解决我问题的最佳解决方案。

我使用了KnownTypesBinder,实现于:https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm

已知类型绑定器:

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 中的 KnownType 必须预先填充所有要反序列化的非基元类型。

编辑:我目前不接受自己的答案,因为我不知道如何处理复杂类型的列表。例如,如果一个人有一个列表和一个列表,当类型名称是"List'1"并且可能是其中之一时,您会返回什么类型。

编辑以下版本的 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();
}
}

最新更新