https://kotlinlang.org logo
#http4k
Title
# http4k
k

King River Lee

09/21/2023, 2:37 AM
I have a issue about LENS. when I use
Map<String, Any?>>
as input json, to get map from req. it parse json number 5 to
java.math.BigIntger
rather than
<http://kotlin.Int|kotlin.Int>
. any one knows why? or How can I fix it?
{"number" : 5}
parse to
mapof("number" to 5)
. the 5 in kotlin map is a
java.math.BigIntger
here is my code and debug info
a

Andrew O'Hara

09/21/2023, 3:02 AM
JSON doesn't really have type information, and most marshallers can barely differentiate between integers and decimals. There's no way for the marshaller to know the maximum size of the number, so my best guess is that it chose the safest option, which is BigInteger. You wouldn't want it to return an Int one time, and then a Long another time, would you?
k

King River Lee

09/21/2023, 3:09 AM
Ok, I see. so I need to handle the BigIntger myself. got it.
s

s4nchez

09/26/2023, 8:45 AM
If you're using Jackson, that can be configured centrally (i.e. you don't have to handle BigIntegers yourself). Here's an example:
Copy code
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.http4k.format.ConfigurableJackson
import org.http4k.format.asConfigurable

data class Foo(val bar: Int)

object CustomJackson : ConfigurableJackson(
    KotlinModule.Builder().build()
        .asConfigurable()
        .done()
        .configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, false)
)

fun main() {
    val jsonExample = """{"bar":123}"""

    val foo = CustomJackson.asA<Foo>(jsonExample)
    println(foo)
}
This will automatically serialise to
Int
rather than
BigInteger
😉
@King River Lee The default config for Jackson in http4k is to use BigInteger/BigDecimals, but that can be customised if you're confident that the values you'll receive fit in an Int 😉