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

Johnny Baloney

02/07/2022, 4:22 PM
Hello, I was browsing Ktor related resources and came across Ktor 1.3 release notes. There I found this snippet:
Ktor now supports a way to construct a JSON body using the
kotlinx.serialization
DSL:
Copy code
<http://client.post|client.post>("<http://localhost:9090>") {
contentType(ContentType.Application.Json)
body = json {
"key1" to 123
"map" to json {
"key2" to "abc"
}
}
}
To use it on a client, install JsonFeature and add the ktor-client-serialization dependency.
When I paste this into the editor
json
function is not recognised. How do I enable the kotlinx.serialization DSL?
a

Angel Mitev

02/07/2022, 7:55 PM
I'm a little fresh, but I'd suggest to go through this https://ktor.io/docs/kotlin-serialization.html
a

Aleksei Tirman [JB]

02/08/2022, 7:44 AM
The Ktor 1.3 is a kind of outdated version. Please use this topic in the documentation as a reference. The equivalent code for Ktor 1.6.7 is the following:
Copy code
val client = HttpClient(Apache) {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
}

<http://client.post|client.post>("<http://localhost:9090>") {
    contentType(ContentType.Application.Json)
    body = buildJsonObject {
        put("key1", 123)
        putJsonObject("map") {
            put("key2", "abc")
        }
    }
}
👍 1
j

Johnny Baloney

02/08/2022, 10:23 AM
Excellent, that's what I needed. I had read through the linked topics and sadly there was no mention there on how to put together a payload by hand. That old release notes document was the only place where I found notes on that. 1.6.7 was what I was playing with and I downgraded to 1.3 to see if I could make it work, but still no joy. In the end I figured I could do something like this but it wasn't as nice as what the document showed:
Copy code
body = JsonObject(
  mapOf(
    "id" to JsonPrimitive(3),
    "title" to JsonPrimitive("some title"),
    "author" to JsonPrimitive("some author")
  )