Nilto
06/19/2024, 12:19 PMobject DefaultIntSerializer : KSerializer<Int> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("DefaultInt", <http://PrimitiveKind.INT|PrimitiveKind.INT>)
override fun serialize(encoder: Encoder, value: Int) {
encoder.encodeInt(value)
}
override fun deserialize(decoder: Decoder): Int {
if (decoder is JsonDecoder) {
val jsonElement = decoder.decodeJsonElement()
return runCatching {
when (jsonElement) {
is JsonPrimitive -> {
if (jsonElement.isString) {
jsonElement.content.toInt()
} else {
<http://jsonElement.int|jsonElement.int>
}
}
else -> throw SerializationException("Unexpected JSON token: $jsonElement")
}
}.onFailure {
println("Warning: Default value used for Int field due to error: ${it.message}")
}.getOrDefault(0)
} else {
throw SerializationException("Expected JsonDecoder for DefaultIntSerializer")
}
}
}
val DefaultReportingModule = SerializersModule {
contextual(String::class, DefaultStringSerializer)
contextual(Int::class, DefaultIntSerializer)
contextual(Boolean::class, DefaultBooleanSerializer)
contextual(Double::class, DefaultDoubleSerializer)
}
However, annotating every model property with @Contextual seems tedious, so I'm thinking of using a compiler plugin to automatically add it to the properties of specific classes.
Are there any problems with my approach? If so, can you recommend an alternative way to solve this problem?Nilto
06/19/2024, 12:27 PMNilto
06/19/2024, 12:29 PMglureau
06/19/2024, 1:09 PMNilto
06/19/2024, 2:12 PMglureau
06/19/2024, 3:04 PMephemient
06/19/2024, 3:35 PMNilto
06/20/2024, 11:14 AMephemient
06/20/2024, 11:09 PMval json = Json { ... }
IgnoreTypeErrorsFormat(json).decodeFromString<T>(...)
and behave similarly to json.decodeFromString(...)
except that you get nulls or 0's instead of type mismatchesNilto
06/21/2024, 3:31 AMephemient
06/21/2024, 3:46 AM