Quick question about JSON serialziation. I receive...
# serialization
c
Quick question about JSON serialziation. I receive this beautiful JSON
{"actual":"","target":null}
but both values are supposed to be
Float?
. I already use
coerceInputValues
to allow string values to be parsed but the
""
doesn’t get translated to
null
or something. Is there a way I can tell Kotlin to use the default value if it can’t deserialize something?
Otherwise that’s my solution:
Copy code
class OctoSafeFloatSerializer : KSerializer<Float?> {

    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Float", PrimitiveKind.FLOAT)

    override fun deserialize(decoder: Decoder): Float? = try {
        decoder.decodeFloat()
    } catch (e: Exception) {
        null
    }

    @OptIn(ExperimentalSerializationApi::class)
    override fun serialize(encoder: Encoder, value: Float?) = value?.let { encoder.encodeFloat(it) } ?: encoder.encodeNull()
}
Copy code
@Serializable(with = OctoSafeFloatSerializer::class) val actual: Float? = null,