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

Antonio Acuña Prieto

02/24/2024, 1:10 PM
Hi! Do you know how to set body on a POST query using Ktor client without creating a new class to parse? Maybe using object?
h

Harold Martin

02/24/2024, 3:44 PM
a

Antonio Acuña Prieto

02/24/2024, 6:49 PM
Does it work with Jackson?
a

Aleksei Tirman [JB]

02/26/2024, 8:12 AM
If you use Jackson, you can create an
ObjectNode
object using the
ObjectMapper
. Here is an example:
Copy code
val client = HttpClient(CIO) {
    install(ContentNegotiation) {
        jackson()
    }
}

val mapper = ObjectMapper()
val rootNode: ObjectNode = mapper.createObjectNode()

val childNode1: ObjectNode = mapper.createObjectNode()
childNode1.put("name1", "val1")
childNode1.put("name2", "val2")
rootNode.set<ObjectNode>("obj1", childNode1)
rootNode.set<TextNode>("data", TextNode("value"))

val response = <http://client.post|client.post>("<https://httpbin.org/post>") {
    setBody(rootNode)
    contentType(ContentType.Application.Json)
}

println(response.bodyAsText())
🙇 1