使用JSON.NET反序列化到派生类

时间:2014-04-16 08:13:01

标签: 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 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_typeapplication/x-directory)或者Video对象(如果content_typevideo/x-matroska)。

简单的解决方案是将所有内容反序列化到基类,然后将它们转换为各自的派生类,但我发现这没有效果,所以我想知道是否还有其他解决方案!

提前感谢您的意见。

1 个答案:

答案 0 :(得分:0)

我的一位朋友向我指出这篇文章解决了我的问题:

Deserializing heterogenous JSON array into covariant List<> using JSON.NET

我只是尝试过,对于我的情况,改编的代码是这样编写的:

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