1

The documentation here shows that when serializing an object that implements an interface, as long as the subclass is @Serializable, it will be able to serialize it. However, this serializes a number of properties that are on the subclass that I don't want to be serialized.

example:

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

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

When I serialize this, the property "dontWantSerialized" ends up in the json as well. I want to create a json payload with only the properties from the interface. Is this possible? I would also not like it to require the "type" property as well, since I only expect one implementation of the interface within the compilation unit. Is there any way to accomplish this with kotlinx serialization?

FatalCatharsis
  • 3,407
  • 5
  • 44
  • 74

1 Answers1

0

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

Add @kotlinx.serialization.Transient to any property that you do not wish to be serialized

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

When defining your serializer modules add a default serializer:

Json {
  this.serializersModule = SerializersModule {
    polymorphic(Test::class) {
      subclass(TestImpl::class, TestImpl.serializer())
      this.default { TestImpl.serializer() }
    }
  }
}
Tom
  • 3,711
  • 2
  • 25
  • 31
  • For the second part, I tried what you suggested [here](https://pastebin.com/QQV3JWCD) and I still get the result `{"type":"TestImpl","prop1":"blah","prop2":"blah"}`. I saw that [section](https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#default-polymorphic-type-handler-for-deserialization) at the bottom, and I now see what you're talking about, but this behavior is still unexpected. Why does it still include type? – FatalCatharsis Jun 23 '21 at 18:48
  • @FatalCatharsis Adding `default` helps with decoding without having `type` in the json. The way you serialize is using a polymorphic serializer, which is the equivalent of doing `encoder.encodeToString(PolymorphicSerializer(Test::class), data)` which adds the `type`. If you do not want it to add a discriminator, you can serialize with the specific class serializer. e.g. `encoder.encodeToString(TestImpl.serializer(), data)` or `encoder.encodeToString(data)` – Tom Jun 24 '21 at 06:23