There is an Event
sealed interface with UserConnected
and EstimationSent
implementations.
data class User(
val id: String,
val displayName: String,
)
sealed interface Event {
val id: String
}
data class UserConnected(
override val id: String,
val user: User,
) : Event
data class EstimationSent(
override val id: String,
val userId: String,
val estimation: Int,
) : Event
These classes living in a 3rd-party module, thus cannot be annotated or modified.
Is it possible to make the Event
sealed interface with its implementations serializable producing the following JSON?
UserConnected:
{
"eventId": "string",
"data": {
"userId": "string",
"userDisplayName": "string"
}
}
EstimationSent:
{
"eventId": "string",
"data": {
"userId": "string",
"estimation": 42
}
}
The goal would be to have a polymorphic serialization which possibly type-safe.
I have tried to implement a custom KSerializer
and register it like this:
val format = Json {
serializersModule = SerializersModule {
polymorphic(Event::class) {
subclass(UserConnected::class, UserConnectedSerializer)
subclass(EstimationSent::class, EstimationSentSerializer)
}
}
}
However, this solution does not provide compile-time error if there is a missing KSerializer
for an Event
implementation.