(JSON)数据合同中的复杂继承模式

时间:2016-03-01 19:37:06

标签: c# json oop inheritance json.net

我必须处理可以采用以下形式的序列化数据:

{
    "CommonKey" : "Value",
    "ObjType" : "A",
    "Obj" : {
        "CommonObjKey" : "Value"
        "ObjKey" : "Value"
    }
}

OR

{
    "CommonKey" : "Value",
    "ObjType" : "B",
    "Obj" : {
        "CommonObjKey" : "Value"
        "ObjKey" : 1234
    }
}

请注意,ObjKey可以是字符串或整数,具体取决于类型。

如果在C#中允许重载派生的返回类型,则可以对其进行建模:

abstract class ContractBase 
{ 
    string CommonKey;
    string ObjType;
    abstract ObjBase Obj; 
}

class AContract : ContractBase { override AObj Obj; }
class BContract : ContractBase { override BObj Obj; }

abstract class ObjBase { string CommonObjKey; }

class AObj : ObjBase { string ObjKey; }
class BObj : ObjBase { int ObjKey; }

是否有推荐的方法来建模这种数据模式?要求是:

  1. 我可以使用JSON.NET
  2. 轻松地反序列化它
  3. 我可以在90%的时间内使用基本类型,只在需要A或B特定字段时才使用它。

1 个答案:

答案 0 :(得分:1)

我建议将dyanmic用于没有一致类型的属性(ObjKey)。

可能的实施:

var cb1 = new ContractBase
{
    CommonKey = "Value",
    ObjType = "A",
    Obj = new Obj
    {
        CommonObjKey = "Value",
        ObjKey = 1234
    }
};

var cb2 = new ContractBase
{
    CommonKey = "Value",
    ObjType = "A",
    Obj = new Obj
    {
        CommonObjKey = "Value",
        ObjKey = "Value"
    }
};

class ContractBase 
{
    public string CommonKey { get; set; }
    public string ObjType { get; set; }
    public Obj Obj { get; set; }
}

class Obj
{
    public string CommonObjKey { get; set; }
    public dynamic ObjKey { get; set; }
}

请注意,您可以使用object代替dynamic,但dynamic可以减少投射的需要,从而使代码更易于阅读和理解。