反序列化JSON成多个继承类

Deserialize JSON into multiple inherited classes

当我从 DocumentDB 中序列化我的 JSON 对象时,我的 Control 没有反序列化为 OptionsControlOptions 属性。

我有以下 class, Control:

public class Control : IControl
{
    public Guid Id { get; set; }

    public virtual Enums.ControlType Type { get; set; }

    public string PropertyName { get; set; }

    public string ControlCssClass { get; set; }

    public string Description { get; set; }
}

我也有OptionsControl,继承自Control:

public class OptionsControl : Control
{
    public IDictionary<string, string> Options;
}

我也有一个ClickableControl:

public class ClickableControl : Control
{
    public string Url { get; set; }
    public string UrlTarget { get; set; }
}

我使用 Azure 中的文档资源管理器将此 JSON 放入 DocumentDB documentcollection:

Rows:
[
    {
        Controls:
        [
            {
              "PropertyName": "Relationship",
              "ControlCssClass": "",
              "Description": "",
              "Type": 3,
              "Options": [
                  {
                    "Key": "Spouse",
                    "Value": "Spouse"
                  },
                  {
                    "Key": "Child",
                    "Value": "Child"
                  },
                  {
                    "Key": "Step-child",
                    "Value": "Step-child"
                  }
              ],
           }
        ]
    }
]

当我从 DocumentDB 中提取数据时,我尝试将其序列化到我的 Row class:

public class Row
{
    public IList<Control> Controls { get; set; }
}

我需要能够将任何类型的 "Control" 放入 DocDB 的控制列表中,并让 C# 将该列表反序列化回正确的 Control class(即基础 Control class,或 OptionsControlClickableControl).

等派生词之一

问题是因为我正在反序列化为 Control,所以我获得了控件上除 Options 之外的所有属性。或者,如果我尝试反序列化具有 UrlUrlTarget 的控件,我只会获得基本的 Control 属性,而不是 URL 属性。我以为 C# 会处理将反序列化对象转换为 OptionsControl 或 ClickableControl,但我猜这是不正确的?我需要做什么才能使 DocumentDB 中的 JSON 对象正确序列化并变成 OptionsControl(具有选项 属性)而不仅仅是基本控件?

您可以尝试使用 Json.NET 自己序列化您的对象,然后将序列化的内容发布到 DocumentDb 中。然后,当您需要数据时,将其作为 json 字符串读回并再次使用 Json.NET 进行反序列化。 Json.NET 可以处理继承,所以你只需要配置它来了解你的类型层次结构。使用 TypeNameHandling 设置:

http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
};