【发布时间】:2014-04-16 08:13:01
【问题描述】:
我已经为此奋斗了几个小时,但我无法找到解决方案。 使用 JSON.NET,我试图将一些数据反序列化为一个或另一个派生类,但我想基于这些数据中实际存在的字段来定位正确的派生类......
这是一个简化的例子:
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_type 字段的 JSON.NET 来实例化 Directory 对象(如果 content_type 是 application/x-directory)或 Video 对象(如果 @ 987654328@ 是video/x-matroska)。
简单的解决方案是将所有内容反序列化到基类,然后将它们转换为各自的派生类,但我觉得这不是有效的,所以我想知道是否还有其他解决方案!
提前感谢您的意见。
【问题讨论】:
标签: c# json derived-class json-deserialization