xenomachina
12/04/2024, 8:45 AMFoo with a KSerializer...
@Serializable(with = FooAsStringSerializer::class)
class Foo(value: String) {
...
}
object FooAsStringSerializer : KSerializer<Foo> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Foo", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Foo) {
encoder.encodeString(value.toString())
}
@Throws(SerializationException::class)
override fun deserialize(decoder: Decoder): Foo {
val string = decoder.decodeString()
return try {
Foo(string)
} catch (exc: Exception) {
throw SerializationException("Can't deserialize Foo \"$string\"", exc)
}
}
}
And I use it in a serializable class Quux like this...
@Serializable
data class Quux(
val foo: Foo? = null,
// other fields go here
)
@OptIn(ExperimentalSerializationApi::class)
val jsonFormat: Json = Json {
// try to be as permissive as possible
ignoreUnknownKeys = true
allowTrailingComma = true
allowComments = true
isLenient = true
coerceInputValues = true
}
...and I try to deserialize JSON for a Quux with an invalid string for foo, the entire deserialization of the Quux fails.
I want deserialization of Quux instances to be as permissive as possible, so if foo can't be deserialized for any reason, I'd like it to just be set to null.
What's the "right" way to do this?Emil Kantis
12/04/2024, 1:40 PMFoo? which swallows the decoding exceptions basically.. I did something similar here https://github.com/Kantis/ks3/pull/110/filesxenomachina
12/04/2024, 4:31 PMJson), but I think I can get this to work for my case.
Thank you, @Emil Kantis.