System.Text.Json序列化未使用派生类



我有一个名为Extension的抽象类,它有几个派生类,如DerivedExtensionADerivedExtensionB等。

现在我有一个定义为List<Extension>的列表,其中包含派生类实例。

现在,如果我序列化上面的列表,它只序列化Extension中的基类属性,因为该列表具有基类Extension类型。如果我将列表定义为List<DerivedExtensionA>,然后只在其中放置DerivedExtensionA的实例,那么它们就可以串行化了。但我的代码是通用的,应该接受所有类型的扩展,所以这对我来说不是一个可行的解决方案

所以问题是。。

如何将列表定义为List<Extension>,并且仍然能够完全序列化包含其所有属性的派生类实例?

这是一把小提琴,展示了这种行为:https://dotnetfiddle.net/22mbwb

编辑:已更正fiddle URL

从如何使用System.Text.Json 序列化派生类的属性

不支持多态类型层次结构的序列化。

在你的小提琴中,你可以使用一组对象:

string allExtensionsSerialized =
JsonSerializer.Serialize((object[])allExtensions.ToArray());

这是我最近使用的破解:

public record MyType(
// This nonsense is here because System.Text.Json does not support normal polymorphic serialisation
[property: JsonIgnore] List<X> Messages))
{
// This nonsense is here because System.Text.Json does not support normal polymorphic serialisation
[JsonPropertyName("Messages")]
public object[] MessagesTrick => Messages.ToArray();

为了取消序列化,我决定在专用的FromJson(string json)方法中使用JsonDocument.Parse。在这种特殊情况下,这对我来说还可以。

实际上,我最终将列表的定义从List<Extension>更改为List<object>,并且行为得到了纠正。对于阅读本文的每个人来说,这可能不是一个可行的解决方案,但对我来说很好,所以这就是我添加自己答案的原因。