插件和依赖:
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)
任何帮助,将不胜感激。