Ayfri
04/19/2022, 7:50 PMvalue
field, using an interface to ensure that field exists), and deserialize as the enum value
For now I have the serializer working and it was pretty easy, but what should be the deserializer ?ephemient
04/19/2022, 7:59 PMEnum.ordinal
or Enum.name
you have to build your own reverse mappingAyfri
04/19/2022, 8:01 PMephemient
04/19/2022, 8:02 PMAyfri
04/19/2022, 8:06 PM@Serializable
sealed interface EnumAsInt {
val value: Int
}
class EnumAsIntSerializer<T>(private val enum: T) : KSerializer<T> where T : EnumAsInt, T : Enum<*> {
override val descriptor = Int.serializer().descriptor
override fun deserialize(decoder: Decoder): T {
return enum::class.java.enumConstants.first { it.value == decoder.decodeInt() }
}
override fun serialize(encoder: Encoder, value: T) {
encoder.encodeInt(value.value)
}
}
Is this right ?ephemient
04/19/2022, 8:15 PMephemient
04/19/2022, 8:17 PMAyfri
04/19/2022, 8:18 PMephemient
04/19/2022, 8:19 PMabstract class EnumAsIntSerializer<T : EnumAsInt>(private val values: Array<T>) { ... }
@Serializable(with = MyEnum.Serializer::class)
enum class MyEnum : EnumAsInt {
object Serializer : EnumAsIntSerializer<MyEnum>(enumValues())
}
Ayfri
04/19/2022, 8:21 PM