Ber*_*ens 6 c# inheritance serialization json 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; }
}
Run Code Online (Sandbox Code Playgroud)
序列化一些虚拟对象:
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);
Run Code Online (Sandbox Code Playgroud)
当前将生成的 Json:
{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A"}{"MyProperty":"Test my MyProperty B"}]}
Run Code Online (Sandbox Code Playgroud)
我想要的 Json:
{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A","AnotherPropertyA":"Test AnotherPropertyA"},{"MyProperty":"Test my MyProperty B","AnotherPropertyB":"Test AnotherPropertyB"}]}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢你!
Xtr*_*tes -1
如果您不想像这样序列化属性,请使用 Ignore 属性来装饰属性
public class DerivedClassA : BaseClass
{
[JsonIgnore]
public string AnotherPropertyA { get; set; }
}Run Code Online (Sandbox Code Playgroud)