If I have a class `Foo` with a `KSerializer`... ``...
# serialization
x
If I have a class
Foo
with a
KSerializer
...
Copy code
@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...
Copy code
@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?
e
I think you'd need to create a serializer for
Foo?
which swallows the decoding exceptions basically.. I did something similar here https://github.com/Kantis/ks3/pull/110/files
x
Very interesting! I was hoping there was something simpler (like an option in
Json
), but I think I can get this to work for my case. Thank you, @Emil Kantis.