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

Suresh Maidaragi

11/21/2023, 10:34 AM
Hi there, how to ignore
null
values from HTTP post body
b

Berkay Özkan

11/21/2023, 10:37 AM
Can you share example json? If you mean you dont want to deserialize some fields that you dont care you can use
Copy code
install(ContentNegotiation) {
    json(
        Json {
            ignoreUnknownKeys = true
        },
    )
}
s

Suresh Maidaragi

11/21/2023, 10:45 AM
Copy code
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class LoginRequestBody(
    @SerialName("name")
    val name: String,
    @SerialName("last_name")
    val lastName: String?=null,
    @SerialName("password")
    val password: String?=null
)
Copy code
suspend fun postLogin(loginBody: LoginRequestBody): HttpResponse {
    return httpClient.post("url") {
        contentType(ContentType.Application.Json)
        setBody(loginBody)
    }
}
In this above code I don't want to post the key
lastName
to http post request, because it can be
null
. Whenever
lastName
is null I want to ignore in post
requestbody
b

Berkay Özkan

11/21/2023, 12:20 PM
Copy code
val r = LoginRequestBody("Test")
val x = Json.encodeToString(r)
println(x)
default behavior will be
Copy code
{
  "name": "Test"
}
s

Suresh Maidaragi

11/21/2023, 12:27 PM
awesome thanks @Berkay Özkan 🙏