dave08
03/09/2023, 12:19 PM{ "foo": "" }
be null in this: data class Foo(value: Int? = null)
? (It's supposed to be a number when not an empty string...)Adam S
03/09/2023, 12:28 PMJsonPrimitive
and the expose the actual value as a property
data class Foo(
private val value: JsonPrimitive? = null
) {
val actualValue = value?.myConverterFunction()
}
dave08
03/09/2023, 12:32 PMephemient
03/09/2023, 12:38 PMephemient
03/09/2023, 12:39 PM@Serializable(with = Foo.Serializer::class)
data class Foo(val value: Int? = null) {
@Serializable
data class Surrogate(val value: JsonPrimitive = JsonNull)
object Serializer : KSerializer<Foo> {
override val descriptor: SerialDescriptor = SerialDescriptor("Foo", Surrogate.serializer().descriptor)
override fun serialize(encoder: Encoder, value: Foo) {
val surrogate = Surrogate(value = JsonPrimitive(value.value))
encoder.encodeSerializableValue(Surrogate.serializer(), value)
}
override fun deserialize(decoder: Decoder): Foo {
val surrogate = decoder.decodeSerializableValue(Surrogate.serializer())
return Foo(value = surrogate.value.intOrNull)
}
}
}
dave08
03/09/2023, 12:43 PMAdam S
03/09/2023, 12:46 PM@Serializable
value class IntConverter(private val value: JsonPrimitive) {
val actual get() = { value.myConverter... }
}
Then you can re-use the same class in your data class
data class Foo(
private val value: IntConverter? = null
)
ephemient
03/09/2023, 12:50 PMFoo(value = IntConverter(JsonPrimitive("0"))) != Foo(value = IntConverter(JsonPrimitive("-0")))
even though you would want to consider them the same valueAdam S
03/09/2023, 12:51 PM