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

gmariotti

01/26/2023, 12:39 PM
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

Aleksei Tirman [JB]

01/26/2023, 2:02 PM
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

gmariotti

01/26/2023, 3:06 PM
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

Aleksei Tirman [JB]

01/26/2023, 3:50 PM
The
null
is a valid JSON value (https://www.json.org/json-en.html).
g

gmariotti

01/26/2023, 3:53 PM
My bad 😓, I never realized that
null
could be used as a top level value for json
47 Views