kotlinktorhttp-status-code-406klaxon

Getting 406 Not Acceptable when Ktor serializes the object


Why am I getting 406 Not Acceptable when I return the ApiResponse (the commented out line) and let Ktor serialize it vs doing the in-code Klaxon serialization directly?

    route("/hello") {
        get {
            println("hello there...")
            println("Hello, ${call.principal<JWTPrincipal>()?.subject}!")

            call.respond(Klaxon().toJsonString(ApiResponse(body = "Nothing found")))
//            call.respond(ApiResponse(body = "Nothing found"))

        }

ApiResponse:

import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable

@Serializable
data class ApiResponse(
    val error: Boolean? = false,
    val errorMessage: String? = null,
    @Contextual
    val body: Any? = null
)


Solution

  • The Any type isn't serializable so you need to replace Any with the generic type:

    @Serializable
    data class ApiResponse<T>(
        val error: Boolean? = false,
        val errorMessage: String? = null,
        @Contextual
        val body: T? = null
    )