ankushg
06/08/2023, 10:53 PMenum 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 appropriatelychr
06/08/2023, 11:53 PMEmil Kantis
06/09/2023, 6:54 AMankushg
06/10/2023, 4:34 PMEmil Kantis
06/12/2023, 6:34 AMcoerceInputValues = 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.
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)
}