```enum class Cookie { ChocolateChip, Oatm...
# serialization
r
Copy code
enum class Cookie {
    ChocolateChip,
    Oatmeal,
}

fun main() {
    val cookieSerializer: KSerializer<Cookie> = EnumSerializer<Cookie> { // custom helper function
        when(it) {
            Cookie.ChocolateChip -> "chocolate-chip"
            Cookie.Oatmeal -> "oatmeal"
        }
    }
    val json = Json {
        serializersModule = SerializersModule {
            contextual<Cookie>(cookieSerializer)
        }
    }
    json.decodeFromJsonElement<Cookie>(cookieSerializer, JsonPrimitive("chocolate-chip")) // works as intended
    json.decodeFromJsonElement<Cookie>(JsonPrimitive("chocolate-chip")) // throw exception
}
I am trying to deserialize enum values with a custom serializer defined in the serializer module ignoring the default serializer of Enums. The last call however results in SerializationException: Cookie does not contain element with name 'chocolate-chip'. How can I make the decoder consider my custom serializer?
t
You’ve only defined a
Serializer
. It knows how to make
Cookie.ChocolateChip
into
chocolate-chip
, but without a
Deserializer
, it has no idea how to go back the other way.
r
Hey Todd, my custom Serializer is alright. In creates a map in the helper function so that I only have to define the mapping once. I reworked the code example. The point is that
json.decodeFromJsonElement<Cookie>(cookieSerializer, JsonPrimitive("chocolate-chip"))
works but the other using contextual does not.