gmariotti
01/26/2023, 12:39 PMreceiveNullable
works and when I'm supposed to use it? Specifically, with a server like
fun Application.ktorMain() {
install(ContentNegotiation) {
jackson()
}
routing {
post {
val response = call.receiveNullable<RequestBody>()
if (response == null) call.respond("null") else call.respond(response)
}
}
}
data class RequestBody(val test: String)
I would expect this test to pass and, instead, it fails (the exception is JsonConvertException
)
class AppTest {
@Test
fun `body is null`() = testApplication {
val response = <http://client.post|client.post>("/") {
headers { header(HttpHeaders.ContentType, ContentType.Application.Json) }
}
assertEquals(HttpStatusCode.OK, response.status)
assertEquals("null", response.bodyAsText())
}
}
Aleksei Tirman [JB]
01/26/2023, 2:02 PMreceiveNullable
method allows you to deserialize JSON into a nullable type. It doesn’t mean you don’t need to send a request body. Here is the rewritten test that passes:
class KtorTest {
@Test
fun `body is null`() = testApplication {
application {
ktorMain()
}
val response = <http://client.post|client.post>("/") {
setBody("null")
contentType(ContentType.Application.Json)
}
assertEquals(HttpStatusCode.OK, response.status)
assertEquals("null", response.bodyAsText())
}
}
fun Application.ktorMain() {
install(ContentNegotiation) {
jackson()
}
routing {
post("/") {
val response = call.receiveNullable<RequestBody?>()
if (response == null) call.respond("null") else call.respond(response)
}
}
}
gmariotti
01/26/2023, 3:06 PMPOST/PUT
without body makes no real sense, but why having an invalid body like "null"
be able to return a nullable but not a missing body?Aleksei Tirman [JB]
01/26/2023, 3:50 PMnull
is a valid JSON value (https://www.json.org/json-en.html).gmariotti
01/26/2023, 3:53 PMnull
could be used as a top level value for json