在不知道实体类型的情况下反序列化实体

本文关键字:实体 情况下 反序列化 类型 不知道 | 更新日期: 2023-09-27 18:02:11

我在我的项目中遇到了这个问题,我有一个json字符串从表,它是一个序列化的实体。

Json

{
"Entity":{
"__type":"Book:#Definition",
"BookId":3,
"BookName":"Meloon Dreams",
"Type":2,
"Price":35
}
}
Book类

namespace Definition
{
   [DataContract]
   public class Book : IEntity
   {
       [DataMember]
       public int BookId { get; set; }
       [DataMember]
       public string BookName { get; set; }
       [DataMember]
       public BookType Type { get; set; }
       [DataMember]
       public decimal Price { get; set; }
   }
}
<<p> 工作流类/strong>
public class Workflow
{
    public int WorkflowId { get; set; }
    public IEntity Entity { get; set; }
}

因此,在控制器类中,我从表中获得json字符串,我想将其反序列化为自己的类型。但是,只有json字符串中的__type可以帮助我确定它的类型。我的意思是

workflow.Entity = Serializer.JsonDeserialize<IEntity>(jsonString);

我需要用Book代替IEntity

在不改变类结构的情况下,是否可以从json中获取类型并将其转换为类型并将其替换为IEntity?

在不知道实体类型的情况下反序列化实体

如果我正确理解了这个问题,您应该希望动态地实例化指定泛型类型的泛型类。可以通过反射来实现:

// Load type name from json - you'll need to implement LoadTypeFromJson() method to load type name string from json
string typeName = LoadTypeFromJson();
// Get .Net Type by type name
Type entityType = Type.GetTypeByName(typeName);
// Get Serializer type
Type serializerType = typeof(Serializer);
// Get MethodInfo for Deserialize method of Serializer class
MethodInfo deserializeMethodInfo = serializerType.GetMethod("Deserialize");
// Construct Serializer.Deserialize<IEntity> method for specific IEntity
MethodInfo constructedDeserializeMethod = deserializeMethodInfo.MakeGenericMethod(entityType);
// Call constructed method
constructedDeserializeMethod.Invoke(null, new object[] { jsonString });

这里的关键部分是MethodInfo。MakeGenericMethod方法

相关文章: