Is there any way to tell kotlinx.serialization tha...
# serialization
p
Is there any way to tell kotlinx.serialization that the class-discriminator for a polymorphic field is defined by a sibling field? i.e.
{"eventType": "MyEventType": "event": { … /*MyEventType fields */ }
or will we need a custom serializer for this?
d
Yes that's how polymorphism current works.
p
I understood the current polymophism to embed the class-discriminator into the object itself, i.e.:
Copy code
@Serializable sealed class EventBase
@Serializable @SerialName("greet") data class GreetEvent(val name: String) : EventBase()
@Serializable data class EventPayload(val event: EventBase)
fun main() = println(Json.encodeToString(EventPayload(GreetEvent("Bob"))))
results in
Copy code
{
  "event": {
    "type": "greet",
    "name": "Bob"
  }
}
but the existing model is declared as
Copy code
{
  "eventType": "greet",
  "event": {
    "name": "Bob"
  }
}
d
Ah I see. You'll need a greet event and a greet event payload then.
p
Yeah I’ve played with that approach and it seems to work for the most part, but makes for a lot of noise and duplication given our EventPayload has 4 fields, and all four would need to be abstract at the root of the hierarchy and defined on each data class leaf. I have managed to achieve something with a custom serializer but I needed to cast the root event serializer as the internal SealedClassSerializer in order to lookup the serializers by type/serialName which I’m not happy with either
d
I currently have this duplication issue and I don't even have the nesting you do. I don't mind it too much but I guess that's subjective.