0

插件和依赖:

id 'org.jetbrains.kotlin.plugin.serialization' version "$kotlin_version"
implementation "io.ktor:ktor-serialization:$ktor_version"

Application文件:

fun main() {
    embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
        install(ContentNegotiation) {
            json()
        }

        userRouter()
    }.start(wait = true)
}

UserRouter

fun Application.userRouter() {
    routing {
        get("/users/{id}") {
            val id = call.parameters["id"]?.toInt() ?: -1
            val user = User("Sam", "sam@gmail.com", "abc123")

            val response = if (id == 1) {
                Response("hahaha", false)
            } else {
                Response(user, true)        //< - here, use String type will work
            }

            call.respond(response)
        }
    }
}

User

@Serializable
data class User(
    val name: String,
    val email: String,
    val password: String
)

Response

@Serializable
data class Response<T>(
    val data: T,
    val success: Boolean
)

日志:

2021-12-02 18:04:34.214 [eventLoopGroupProxy-4-1] ERROR ktor.application - Unhandled: GET - /users/7
kotlinx.serialization.SerializationException: Serializer for class 'Response' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
    at kotlinx.serialization.internal.Platform_commonKt.serializerNotRegistered(Platform.common.kt:91)
    at kotlinx.serialization.SerializersKt__SerializersKt.serializer(Serializers.kt:155)

任何帮助,将不胜感激。

4

3 回答 3

2

问题是response变量的类型是(和类型Response<out Any>之间的最小公分母是)并且序列化框架无法序列化该类型。StringUserAnyAny

于 2021-12-03T07:53:43.020 回答
0

这很奇怪,以下工作,但对我来说它们是一样的:

get("/users/{id}") {
    val id = call.parameters["id"]?.toInt() ?: -1
    val user = User("Sam", "sam@gmail.com", "abc123")

   /* val response = if (id == 1) {      //<- determine response here won't work, why?
        Response("hahaha", false)
    } else {
        Response(user, true)
    }

    call.respond(response)*/

    if (id == 1) {
        call.respond(Response("hahaha", false))
    } else {
        call.respond(Response(user, true))
    }
}
于 2021-12-03T16:42:47.423 回答
0

当您将可空泛型设置为 null 时,您应该为泛型指定类型,否则插件不知道如何序列化它。例如。

//define
@Serializable
data class Response<T>(
    val data: T?,
    val success: Boolean
)

///usage:
val response = Response<String>(null, false)
于 2022-01-18T08:50:12.923 回答