kotlinx-serialization - 如何仅序列化接口上的属性

kotlinx-serialization - How to serialize ONLY properties on interface

文档here说明在序列化实现接口的对象时,只要子类是@Serializable,就可以序列化。但是,这会序列化一些我不想序列化的子类上的属性。

示例:

interface Test {
    val prop1 : String
    val prop2 : String
}

@Serializable
class TestImpl(
    override var prop1,
    override var prop2, 
) : Request {
    var dontWantSerialized = 0
}

当我序列化它时,属性“dontWantSerialized”也出现在 json 中。我想创建一个仅包含接口属性的 json 负载。这可能吗?我也不希望它也需要“类型”属性,因为我只希望在编译单元中实现一个接口。有没有办法用 kotlinx 序列化来完成这个?

I want to create a json payload with only the properties from the interface

@kotlinx.serialization.Transient 添加到您不希望序列化的任何 属性

I would also not like it to require the "type" property as well

定义序列化器模块时添加 default 序列化器:

Json {
  this.serializersModule = SerializersModule {
    polymorphic(Test::class) {
      subclass(TestImpl::class, TestImpl.serializer())
      this.default { TestImpl.serializer() }
    }
  }
}