如何禁用 kotlinx 序列化多态鉴别器?

How to disable kotlinx serialization polymorphic descriminator?

我正在为许多第三方 API 生成 JSON。其中许多接受不同对象的列表(JSON 数组),但是,由于列表的多态性,其中 none 将接受由 kotlinx 序列化自动生成的 "type": "com.mycom.someclass"

在我的用例中,我只关心序列化。不需要反序列化。

当前:

[{"type":"com.mycom.Child1","x":"child1"}, {"type":"com.mycom.Child2","y": 23}]

需要:

[{"x":"child1"}, {"y": 23}]

如何禁用此自动行为?

看看Json parametric polymorphic deserialization:

You also can serialize data with such serializer. In that case, either registered or default serializer would be selected for the actual property type in runtime. No class discriminator would be added.

您需要实现 JsonParametricSerializer 并手动 select 序列化程序。由于您不需要支持反序列化,因此实现起来很简单。