Is there a way to force a double to serialize to a...
# serialization
s
Is there a way to force a double to serialize to an int when it is a whole number? Failing that, is there a way to supply a custom serializer for only one class in a sealed class?
I wound up writing a transformer and applying it to that attribute. I wish I had started down that path yesterday. For anyone that is curious.
Copy code
object TrailingZeroKillerJsonSerializer : JsonTransformingSerializer<Double>(
    Double.serializer(), "TrailingZeroKiller"
) {
    override fun writeTransform(element: JsonElement): JsonElement {
        val primitive = element as? JsonPrimitive ?: return element
        val value = primitive.doubleOrNull ?: return element
        if (floor(value) != value) return element

        return JsonPrimitive(value.toInt())
    }
}