【问题标题】:Using JSON.NET to deserialize to a derived class使用 JSON.NET 反序列化为派生类
【发布时间】: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_typeapplication/x-directory)或 Video 对象(如果 @ 987654328@ 是video/x-matroska)。

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

提前感谢您的意见。

【问题讨论】:

    标签: c# json derived-class json-deserialization


    【解决方案1】:

    我的一个朋友给我指出了这篇解决我问题的帖子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多