esensar / kotlinx-serialization-msgpack

MsgPack support for kotlinx.serialization -- msgpack.org[kotlinx.serialization]
https://www.ensarsarajcic.com/kotlinx-serialization-msgpack/
MIT License
44 stars 9 forks source link

Enum serialization is not working #63

Closed Galarzaa90 closed 2 years ago

Galarzaa90 commented 2 years ago

Version

Describe the bug Trying to serialize a object with enums fails with the following error:

SerializationException: Non-serializable class kotlin.Int is not supported by class com.ensarsarajcic.kotlinx.serialization.msgpack.internal.BasicMsgPackEncoder encoder

This is an example enum:

enum class Vocation(val properName: String) {
    NONE("None"),
    DRUID("Druid"),
    SORCERER("Sorcerer"),
    PALADIN("Paladin"),
    KNIGHT("Knight"),
    ELDER_DRUID("Elder Druid"),
    MASTER_SORCERER("Master Sorcerer"),
    ROYAL_PALADIN("Royal Paladin"),
    ELITE_KNIGHT("Elite Knight");

    companion object {
        fun fromProperName(properName: String): Vocation? {
            return values().firstOrNull { it.properName.equals(properName, true) }
        }
    }
}

EnumSerializer from kotlinx-serialization-core-jvm is being used by default. Following it on the debugger, it all goes well until the last line of EnumSerializer.serialize:

override fun serialize(encoder: Encoder, value: T) {
    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.encodeEnum(descriptor, index) //here
}

Where encoder is an instance of BasicMsgPackEncoder. I see that encodeEnum is not implemented in BasicMsgPackEncoder, so that could be part of the issue?

Expected behavior The enum value should be serialized by its value's name (as the JSON serializer does), e.g. DRUID, KNIGHT, etc.

The same object can be serialized without problems using: Json.encodeToString.

esensar commented 2 years ago

This should be fixed in 0.4.3 which was just released.