Thread
#serialization
    m

    Martin Gaens

    2 months ago
    What would be the recommended way to serialize/deserialize money amounts? I'm getting a decimal amount of money from an API and
    BigDecimal
    doesn't have a default serializer. Is the best thing to do creating a serializer for
    BigDecimal
    ?
    e

    ephemient

    2 months ago
    serialize it as a string for portability - many JSON implementations don't support primitive numbers outside of Javascript's range, and that includes kotlinx.serialization
    but yes, just write your own serializer
    object BigDecimalSerializer : KSerializer<BigDecimal> {
        override val descriptor: SerialDescriptor =
            PrimitiveSerialDescriptor("java.math.BigDecimal", PrimitiveKind.STRING)
        override fun serialize(encoder: Encoder, value: BigDecimal) {
            encoder.encodeString(value.toString())
        }
        override fun deserialize(decoder: Decoder): BigDecimal {
            return decoder.decodeString().toBigDecimal()
        }
    }
    m

    Martin Gaens

    2 months ago
    I can't serialize it as a String because the API needs a decimal number. Something like:
    {"money":1.55}
    and not
    {"money":"1.55"}
    e

    ephemient

    2 months ago
    1. can't serialize arbitrary numbers in kotlinx.serialization https://github.com/Kotlin/kotlinx.serialization/issues/1051 2. JSON implementations have no requirement to be able to handle arbitrary numbers https://kotlinlang.slack.com/archives/C7A1U5PTM/p1655820506656319?thread_ts=1655807410.755689&amp;cid=C7A1U5PTM