Hi folks, could anyone help me understand how `rec...
# ktor
g
Hi folks, could anyone help me understand how
receiveNullable
works and when I'm supposed to use it? Specifically, with a server like
Copy code
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
)
Copy code
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())
    }
}
a
The
receiveNullable
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:
Copy code
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)
        }
    }
}
g
may I ask what's the reasoning / limitation behind it? I know that a
POST/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?
a
The
null
is a valid JSON value (https://www.json.org/json-en.html).
g
My bad 😓, I never realized that
null
could be used as a top level value for json