Hi, is there a way to serialize an enum as the ord...
# serialization
a
Hi, is there a way to serialize an enum as the ordinal without adding SerialName for each key ?
e
you can easily define your own serializer,
Copy code
open class EnumOrdinalSerializer<E : Enum<E>>(serialName: String, private val values: Array<E>) : KSerializer<E> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor(serialName, <http://PrimitiveKind.INT|PrimitiveKind.INT>)

    override fun serialize(encoder: Encoder, value: E) {
        val index = values.indexOf(value)
        if (index == -1) {
            throw SerializationException(
                "$value is not a valid enum ${descriptor.serialName}, " +
                        "must be one of ${values.contentToString()}"
            )
        }
        encoder.encodeInt(index)
    }

    override fun deserialize(decoder: Decoder): E {
        val index = decoder.decodeInt()
        if (index !in values.indices) {
            throw SerializationException(
                "$index is not among valid ${descriptor.serialName} enum values, " +
                        "values size is ${values.size}"
            )
        }
        return values[index]
    }

    override fun toString(): String = "EnumOrdinalSerializer<${descriptor.serialName}>"
}
which you can either set as the default serializer for an enum class,
Copy code
@Serializable(with = E1.Serializer::class)
enum class E1 {
    A, B;
    object Serializer : EnumOrdinalSerializer<E1>("E1", values())
}
or just at a specific use-site,
Copy code
enum class E2 {
    C, D;
}

@Serializable
data class Data(
    @Serializable(with = Data.E2Serializer::class)
    val e2: E2,
) {
    private object E2Serializer : EnumOrdinalSerializer<E2>("E2", E2.values())
}
a
I see, thanks !
316 Views