I’m getting this error message `Polymorphic serializer was not found for class discriminator 'batter...
j
I’m getting this error message
Polymorphic serializer was not found for class discriminator 'batteryPercentage', JSON input: {"name":"batteryPercentage","value":70}
Copy code
@JsonClassDiscriminator("name")
interface DeviceAttribute

@Serializable
data class Device(
    val id: String,
    val name: String,
    val icon: String,
    val iconOptions: List<String>,
    val attributes: List<DeviceAttribute> = emptyList(),
    val profiles: List<ActiveProfileMode>?,
)

@Serializable
@SerialName("batteryPercentage")
data class BatteryPercentage(val value: Int) : DeviceAttribute
What am I missing here?
e
Iirc you need to use a sealed class hierarchy to get automatic polymorphic serialization
r
That's open polymorphism, as your base class is an interface. You need to register your subsclasses in a
SerializersModule
. See https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism. Alternatively, you could use a
sealed class
as your base instead, see https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#sealed-classes.
sealed interface
support is a bit flaky right now.
j
I thought the
SerializersModule
was only necessary if one needs a default serialization behavior. Thanks for the help!
e
Copy code
@Serializable
sealed interface DeviceAttribute
should work in the Kotlin 1.6.20+, I see https://github.com/Kotlin/kotlinx.serialization/issues/1869 is still an issue but if you're using it as a property in another serializable class it should be fine
1377 Views