smallufo
01/25/2025, 6:51 PMobject TwoDecimalDoubleSerializer : KSerializer<Double> {
private val decimalFormat = DecimalFormat("#.##")
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Double", PrimitiveKind.DOUBLE)
override fun serialize(encoder: Encoder, value: Double) {
val formattedValue = decimalFormat.format(value).toDouble()
encoder.encodeDouble(formattedValue)
}
override fun deserialize(decoder: Decoder): Double {
return decoder.decodeDouble()
}
}
smallufo
01/25/2025, 6:52 PMclass TwoDecimalDoubleSerializerTest {
@Serializable
data class MyClass(
val value: Double, val nested: NestedClass
)
@Serializable
data class NestedClass(
val innerValue: Double
)
private val json = Json {
prettyPrint = true
serializersModule = SerializersModule {
contextual(Double::class, TwoDecimalDoubleSerializer)
}
}
@Test
fun testSerialize() {
val someObject = MyClass(123.456, NestedClass(789.012))
val jsonString = json.encodeToString(someObject)
println(jsonString)
}
}
it outputs :
{
"value": 123.456,
"nested": {
"innerValue": 789.012
}
}
which is not what I wanted.
what’s the problem here ?smallufo
01/25/2025, 6:53 PMrnett
01/28/2025, 5:53 PMEncoder
that delegates everything but the type you want to change (e.g. encodeDouble
). I'd hope there's better ways nowadays but I haven't needed it in a while