Deserializing an entity without awareness of its type

I came up with this problem in my project, I have a json row from the table, this is a serialized entity.

Json

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

Book class

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; }
   }
}

Workflow class

public class Workflow
{
    public int WorkflowId { get; set; }

    public IEntity Entity { get; set; }
}

So, in the controller class, I get the json string from the table, and I want to deserialize it to my own type. But, only __type inside json string helps me with its type. I mean

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

I need to put Book instead of IEntity

Is this possible without changing the structure of classes, or can I get a type from json and convert it to a type and instead of IEntity instead?

+4
source share
1 answer

, , . :

// 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

0

Source: https://habr.com/ru/post/1651013/


All Articles