Is there a way to mark certain enums as being enco...
# serialization
m
Is there a way to mark certain enums as being encoded as ints rather than strings in JSON?
h
Just write a custom serializer
d
I usually have something like this
Copy code
// Lib

@PublishedApi
internal class OrdinalEnumSerializer<E : Enum<E>>(
    serialName: String,
    private val entries: EnumEntries<E>,
) : KSerializer<E> {

    override val descriptor = PrimitiveSerialDescriptor(serialName, <http://PrimitiveKind.INT|PrimitiveKind.INT>)

    override fun serialize(encoder: Encoder, value: E) {
        encoder.encodeInt(value.ordinal)
    }

    override fun deserialize(decoder: Decoder): E = entries[decoder.decodeInt()]
}

inline fun <reified E : Enum<E>> ordinalEnumSerializer(): KSerializer<E> {
    return OrdinalEnumSerializer(E::class.qualifiedName!!, enumEntries<E>())
}

// Example usage

@Serializable(with = MyEnum.Serializer::class)
enum class MyEnum {
    ONE,
    TWO,
    ;

    internal object Serializer : KSerializer<MyEnum> by ordinalEnumSerializer()
}
If you want a property other than the ordinal, you can define another interface like
interface IntEnum { val intValue: Int }
, constrain
E
to
where E : Enum<E>, E : IntEnum
, and tweak the serializer logic a bit