2

我正在尝试发出 http post 请求,但由于无法理解的原因而失败。

object KtorClient {
val client = HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
 }
}
suspend fun createOwner(url : String = "http://localhost:112/company/owner/register", ownerMapper: OwnerMapper) {
println(ownerMapper)
client.post<Unit>(url){
   body = ownerMapper
}
}

BlockquoteIllegalStateException {message_8yp7un$_0:“发送正文失败。内容具有类型:OwnerMapper 类,但应为 OutgoingContent。”,cause_th0jdv$_0:空,堆栈:“captureStack↵Exception↵RuntimeException↵IllegalSta…↵↵↵↵↵↵↵↵ ↵↵↵↵↵↵↵↵↵promiseReactionJob@[本机代码]”,名称:“IllegalStateException”}

添加序列化插件后,出现此错误:

“找不到类 OwnerMapper 的无参数序列化程序。对于泛型类,例如列表,请明确提供序列化程序。”

我遵循了官方示例,但无法使其运行。我正在使用 Kotlin/Js,以上错误来自浏览器。

4

2 回答 2

1
    val client = HttpClient() {
        install(JsonFeature){
            serializer = KotlinxSerializer()
        }
    }
@Serializable
data class OwnerLoginMapper(
    val email: String? = null,
    val username: String? = null,
    val number: String? = null,
    val credential: String
)
@Serializable
data class Token(
    val token : String
)
var response = client.post<Token>(url){
    contentType(ContentType.Application.Json)
    body = ownerMapper
}
println(response.token)

添加这些依赖项:

implementation("io.ktor:ktor-client-json-js:1.3.2")
implementation("io.ktor:ktor-client-serialization-js:1.3.2")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:0.20.0")

应用这个插件:

    kotlin("plugin.serialization") version "1.3.70"

PS:选择合适的版本号。

于 2020-07-20T12:11:49.923 回答
0

您的OwnerMapper班级是否标记为@Serializable

如果没有——请标记为@Serializable

如果是 - 请您尝试在"Can't locate argument-less serializer for class OwnerMapper. For generic classes, such as lists, please provide serializer explicitly."没有 Ktor 的情况下重现第二个问题 ( )。对我来说,它看起来是序列化的问题,可能缺少一些依赖项。

请同时查看 github 问题:https ://github.com/Kotlin/kotlinx.serialization/issues/278

于 2020-07-16T18:31:41.010 回答