Ron S
01/10/2023, 6:44 PMenum 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?Toddobryan
01/10/2023, 9:08 PMSerializer
. 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.Ron S
01/11/2023, 9:27 AMjson.decodeFromJsonElement<Cookie>(cookieSerializer, JsonPrimitive("chocolate-chip"))
works but the other using contextual does not.