Silly question: is there a way to define a general...
# serialization
a
Silly question: is there a way to define a general-purpose serializer for enums which takes a fallback parameter? e.g., I have an
enum class MyEnum { A, B, UNKNOWN }
and a poorly-versioned API starts responding with
"C"
. I want that to be deserialized as
UNKNOWN
so I can avoid crashes and handle it appropriately
c
Also curious about this but for sealed types
e
I think this is something I'd like to add in https://github.com/Kantis/ks3 Mind if I quote your post?
a
Sure!
e
Btw, you can use a fallback enum value by setting
coerceInputValues = true
and then defining a default value. The downside to that is that you need to remember to set the default in all serializable classes using the enum.
Copy code
val format = Json { coerceInputValues = true }

enum class Foo { Bar, Baz, Unknown }

@Serializable
data class Project(val name: String, val language: String = "Kotlin", val foo: Foo = Foo.Unknown)

fun main() {
   val data = format.decodeFromString<Project>(""" {"name":"kotlinx.serialization","language":null, "foo": "bao" } """)
   println(data) // $ Project(name=kotlinx.serialization, language=Kotlin, foo=Unknown)
}