Is it possible to recursively format all double fi...
# serialization
s
Is it possible to recursively format all double fields into #.## format ? I tried this
Copy code
object 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()
  }
}
and test case :
Copy code
class 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 :
Copy code
{
  "value": 123.456,
  "nested": {
    "innerValue": 789.012
  }
}
which is not what I wanted. what’s the problem here ?
requirement : I don’t want to annotate every double field with some custom TwoDecimalDoubleSerializer or @Contextual , that’s a deep object tree.
r
What I did last time I needed something like this was to create a custom
Encoder
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