【问题标题】:Newtonsoft Including Child Attributes in Serialization of Base Class? [duplicate]Newtonsoft 在基类的序列化中包含子属性? [复制]
【发布时间】:2021-09-14 07:05:46
【问题描述】:

我有两个类看起来像这样:

class BaseClass
{
    public string Property1;
}

class ChildClass : BaseClass
{
    public string Property2;
}

如果我创建一个 ChildClass 的实例,然后将其转换为 BaseClass 并对其进行 Json 序列化,则会显示 ChildClass 的属性。

ChildClass childInstance = new ChildClass() { Property1 = "1", Property2 = "2" };

BaseClass baseInstance = (BaseClass)childInstance;

Console.WriteLine(JsonConvert.SerializeObject(baseInstance, Formatting.Indented));
            
{
  "Property2": "2",
  "Property1": "1"
}

尽管在代码中当然不能从 baseInstance 访问 Property2。

为什么会发生这种情况,有什么好的解决方法吗?

【问题讨论】:

  • 您可能需要自己的ContractResolverThis answer 旨在做相反的事情。
  • 序列化程序序列化实际对象而不是具体的铸造视图。注意,SerializeObject 方法获取对象参数。在您的情况下,您将其转换为 BaseClass,但序列化程序将其视为对象。但它仍然是同一个对象(ChildClass)
  • 次要问题:那些不是“属性”——它们是字段(尽管可以说它们应该是属性)。属性在 .NET 中有特定的含义,但不是这样。

标签: c# json inheritance json.net


【解决方案1】:

SerializeObject 是一个以object 作为参数的非泛型方法——然后它在内部使用.GetType() 来发现对象是什么。因此:您在代码中考虑的类型无关紧要;重要的是对象实际上是什么。从object 参数的角度来看:none 的相关成员是直接可见的。这根本不是障碍。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多