Hi, how can I create a serialiazer for an Enum whe...
# serialization
a
Hi, how can I create a serialiazer for an Enum where it would serialize as an int (from the
value
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 ?
e
if you're not using
Enum.ordinal
or
Enum.name
you have to build your own reverse mapping
a
And is there a way to get the enum values within the deserializer ?
e
not from the descriptor, but if you pass in the enum class then sure
a
Copy code
@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 ?
e
no
well, I suppose you could do that, but you don't have a way to register that serializer
a
Ah, then I didn't understood how to pass the enum class 🤔
e
Copy code
abstract class EnumAsIntSerializer<T : EnumAsInt>(private val values: Array<T>) { ... }

@Serializable(with = MyEnum.Serializer::class)
enum class MyEnum : EnumAsInt {
    object Serializer : EnumAsIntSerializer<MyEnum>(enumValues())
}
a
okay I see, thanks !