使用NewtonSoft Json.NET从基类型集合序列化派生类型的属性



更新:已解决!Json.NET默认情况下似乎确实包含派生类型属性,但由于我的代码中出现错误,派生类型被基类型覆盖,因此没有包含这些属性


我目前正在为学校做一个项目,偶然发现了一个问题。

我需要将一个对象序列化到Json,这是我使用Newtonsoft Json.NET完成的。我试图序列化的对象有一个特定基类的对象列表,但该列表中的对象是具有自己独特属性的派生类型。

目前,只有基类的属性包含在生成的Json中。如果可能的话,我希望Json转换器检测集合中的对象是哪个派生类,并序列化它们的唯一属性。

下面的一些代码是我正在做的一个示例。

我使用的类别:

public class WrappingClass
{
public string Name { get; set; }
public List<BaseClass> MyCollection { get; set; }
}
public class BaseClass
{
public string MyProperty { get; set; }
}
public class DerivedClassA : BaseClass
{
public string AnotherPropertyA { get; set; }
}
public class DerivedClassB : BaseClass
{
public string AnotherPropertyB { get; set; }
}

序列化一些伪对象:

WrappingClass wrapperObject = new WrappingClass
{
Name = "Test name",
MyCollection = new List<BaseClass>();
};
DerivedClassA derivedObjectA = new DerivedClassA
{
MyProperty = "Test my MyProperty A"
AnotherPropertyA = "Test AnotherPropertyA"
};
DerivedClassB derivedObjectB = new DerivedClassB
{
MyProperty = "Test my MyProperty B"
AnotherPropertyB = "Test AnotherPropertyB"
};
wrapperObject.MyCollection.Add(derivedObjectA);
wrapperObject.MyCollection.Add(derivedObjectB);
var myJson = JsonConvert.SerializeObject(wrapperObject);

当前将生成的Json:

{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A"}{"MyProperty":"Test my MyProperty B"}]}

我想要的Json:

{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A","AnotherPropertyA":"Test AnotherPropertyA"},{"MyProperty":"Test my MyProperty B","AnotherPropertyB":"Test AnotherPropertyB"}]}

有什么想法吗?非常感谢。

json的默认行为。NET将包含派生类型的所有属性。你不会得到它们的唯一原因是,如果你在基类型上定义了一个[DataContract],而你没有将其扩展到派生类型,或者你有类似optin序列化等的东西。

如果你不想像那样序列化,用Ignore属性装饰属性

public class DerivedClassA : BaseClass
{
[JsonIgnore]
public string AnotherPropertyA { get; set; }
}

最新更新