JSON
{"Entity":{"__type":"Book:#DeFinition","BookID":3,"Bookname":"Meloon Dreams","Type":2,"Price":35}}
书类
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; } }}
工作流程类
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 Jsonstring typename = LoadTypeFromJson();// Get .Net Type by type nameType entityType = Type.GetTypeByname(typename);// Get Serializer typeType serializerType = typeof(Serializer);// Get MethodInfo for Deserialize method of Serializer classMethodInfo deserializeMethodInfo = serializerType.getmethod("Deserialize");// Construct Serializer.Deserialize<IEntity> method for specific IEntityMethodInfo constructedDeserializeMethod = deserializeMethodInfo.MakeGenericmethod(entityType);// Call constructed methodconstructedDeserializeMethod.Invoke(null,new object[] { JsonString });
这里的关键部分是MethodInfo.MakeGenericMethod method
总结以上是内存溢出为你收集整理的c# – 在不知道其类型的情况下反序列化实体全部内容,希望文章能够帮你解决c# – 在不知道其类型的情况下反序列化实体所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)