C# 使用JSON.NET反序列化到派生类
我已经为此奋斗了几个小时,我想不出一个解决办法。 使用JSON.NET,我试图将一些数据反序列化到一个或另一个派生类,但我希望基于这些数据中实际存在的字段来定位正确的派生类 以下是一个简化的示例:C# 使用JSON.NET反序列化到派生类,c#,json,derived-class,json-deserialization,C#,Json,Derived Class,Json Deserialization,我已经为此奋斗了几个小时,我想不出一个解决办法。 使用JSON.NET,我试图将一些数据反序列化到一个或另一个派生类,但我希望基于这些数据中实际存在的字段来定位正确的派生类 以下是一个简化的示例: public class BaseFile { public string Name{get;set;} } public class Directory : BaseFile { public int FileSize {get;set;} } public class Vide
public class BaseFile {
public string Name{get;set;}
}
public class Directory : BaseFile {
public int FileSize {get;set;}
}
public class Video : BaseFile {
public int Duration{get;set}
}
我收到这些JSON格式的数据:
{
"files": [
{
"content_type": "application/x-directory",
"size": 566686478
},
{
"content_type": "video/x-matroska",
"duration": 50
}
}
现在,我想基于content\u type
字段使用JSON.NET实例化目录
对象(如果content\u type
是application/x-Directory
)或Video
对象(如果content\u type
是Video/x-matroska
)
简单的解决方案是将所有内容反序列化到基类,然后将它们转换为各自的派生类,但我觉得这并不有效,所以我想知道是否还有其他解决方案
提前感谢您的意见。我的一位朋友给我指出了这篇解决我问题的帖子: 我刚刚试过,就我的情况而言,修改后的代码是这样写的:
private BaseFile Create(Type objectType, JObject jObject)
{
var type = (string)jObject.Property("content_type");
switch (type)
{
case "application/x-directory":
return new Directory();
case "video/x-matroska":
return new Video();
default:
return new BaseFile();
}
}