https://kotlinlang.org logo
#ktor
Title
# ktor
j

John Pali

10/15/2021, 12:19 PM
Hi people, kinda new here... was wondering how can I accept a JSON payload in Ktor tried
call.receiveText()
but it gets is to a string - had a look on the docs about serialization, but got quite confused there.
b

Big Chungus

10/15/2021, 12:26 PM
call.receive<MyType>()
e.g. call.receive<JsonObject>()
m

Matteo Mirk

10/15/2021, 12:28 PM
that’s the wrong function, it just reads the request as text. First you have to install content negotiation feature:
Copy code
import io.ktor.features.*
// ...
fun main() {
    embeddedServer(Netty, port = 8080) {
        install(ContentNegotiation)
        // ...
    }.start(wait = true)
}
then register a converter, for example Jackson https://ktor.io/docs/jackson.html#register_jackson_converter. Then you execute what Martynas wrote above, yeah ⬆️
to receive data you ask for a given type of your choice and Ktor will perform deserialization for you https://ktor.io/docs/jackson.html#register_jackson_converter
a

Aleksei Tirman [JB]

10/15/2021, 12:58 PM
Please read the docs about content negotiation and serialization
j

John Pali

10/15/2021, 3:00 PM
I have ContentNegotiation installed.. but when I call
call.receive<Entity>()
I get error that some values are not provided...
b

Big Chungus

10/15/2021, 3:02 PM
Does your json match data class? Is data class annotated as serializable?
j

John Pali

10/15/2021, 3:02 PM
The situation is that my Entity has computed values
Copy code
Entity:
id: Int,
user: User,
value: String,
computedValue: String
and Entity is a DAO for an EntityTable The problem is that calling
call.recieve<Entity>()
yells that I didn't provide
id, user, computedValue
in the payload
b

Big Chungus

10/15/2021, 3:03 PM
Annotate computed values with @JsonIgnore
j

John Pali

10/15/2021, 3:03 PM
Didnt know about @JsonIgnore.
Thanks!
Should also the id (auto incremented) should be annotiated?
b

Big Chungus

10/15/2021, 3:04 PM
Pretty much any serialization framework has something like that as it's a pretty standard problem 😄
j

John Pali

10/15/2021, 3:04 PM
First time using Exposed/Ktor 🙂 Coming from a Python/NodeJS world
6 Views