Hi everyone, I have a question concerning JSON de-...
# kotless
c
Hi everyone, I have a question concerning JSON de-/serialisation with the Kotless DSL: I have an easy example that multiplies two values. Therefore I want to extract a POST body like this:
Copy code
{
  "value1": 20,
  "value2": 3.33
}
The result should look like this:
Copy code
{
  "result": 66.6
}
Am I doing this right?
Copy code
@Post("/multiply")
fun multiply(): String {
    val objectMapper = createObjectMapper()
    val requestBody = KotlessContext.HTTP.request.body?.let { String(it, UTF_8) }
    val request = objectMapper.readValue(requestBody, Request::class.java)
    val result = request.value1 * request.value2
    return objectMapper.writeValueAsString(Response(result))
}
data class Request(
    val value1: BigDecimal,
    val value2: BigDecimal
)

data class Response(
    val result: BigDecimal
)

private fun createObjectMapper() = ObjectMapper().findAndRegisterModules().setSerializationInclusion(NON_NULL)
Is this the only way to extract the body and create a JSON response? Or ist there anything more convenient like
@RequestBody
or to create the JSON response?
t
Have you tried just
fun multiply(value1: Double, value2: Double)
?
Or BigDecimal
c
Give me a sec, I’ll try it.
Unfortunately not:
Same with `Double`:
t
Hm, pretty strange. I have probably removed JSON deserialization and only URL parameters now are considered for such deserialization. In that case the only way is that you proposed 🙂
c
Okay, thanks for your fast reply! We wanted to have a look at the “Ktor way” anyway, so this is no blocker for us right know. But of course would be neat if anything like this is available in the future. 👍🏻
h
I also noticed that form body parameters also don’t seem to get picked up; it appears to be quite literally URL query parameters 😞