如何使用 ktor 解析 jackson 的响应?

How to parse response with jackson using ktor?

我有这个依赖关系:

implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-jackson:$ktor_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.ktor:ktor-client-cio:$ktor_version")
implementation("io.ktor:ktor-client-json:$ktor_version")

ktor 服务器的设置:

fun Application.configureHTTP() {
    install(DefaultHeaders)
    install(CallLogging)
    install(AutoHeadResponse)
    install(Routing)
    install(ContentNegotiation) {
        register(ContentType.Application.Json, JacksonConverter())
        jackson {
            enable(SerializationFeature.INDENT_OUTPUT)
            disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            writerWithDefaultPrettyPrinter()
        }
    }
    install(CORS) {
        method(HttpMethod.Options)
        method(HttpMethod.Put)
        method(HttpMethod.Delete)
        method(HttpMethod.Patch)
        header(HttpHeaders.Authorization)
        header("MyCustomHeader")
//        allowCredentials = true
        anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
    }

}

我想得到关于查克·诺里斯的笑话,所以我做了这个data classes:

data class ChuckNorrisJoke(
    val type: String,
    val value: Map<Any, Any>
)

data class JokeContent(
    val id: Long,
    val joke: String,
    val categories: List<String>
)

最后这是我用来开玩笑的功能:

val client = HttpClient(CIO) {
    install(JsonFeature)
}
suspend fun getChuckNorrisJoke(): ChuckNorrisJoke {
    return client
        .get("http://api.icndb.com/jokes/random")
}

当我调用该方法时,出现此错误:

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalStateException: Fail to find serializer. Consider to add one of the following dependencies: 
 - ktor-client-gson
 - ktor-client-json
 - ktor-client-serialization
    at io.ktor.client.features.json.DefaultJvmKt.defaultSerializer(DefaultJvm.kt:14)
    at io.ktor.client.features.json.JsonFeature$Feature.prepare(JsonFeature.kt:130)
    at io.ktor.client.features.json.JsonFeature$Feature.prepare(JsonFeature.kt:125)
    at io.ktor.client.HttpClientConfig$install.invoke(HttpClientConfig.kt:77)
    at io.ktor.client.HttpClientConfig$install.invoke(HttpClientConfig.kt:74)
    at io.ktor.client.HttpClientConfig.install(HttpClientConfig.kt:97)
    at io.ktor.client.HttpClient.<init>(HttpClient.kt:172)
    at io.ktor.client.HttpClient.<init>(HttpClient.kt:81)
    at io.ktor.client.HttpClientKt.HttpClient(HttpClient.kt:43)
    at com.example.ApplicationKt.<clinit>(Application.kt:109)

无法理解如何正确设置 HttpClient

implementation("io.ktor:ktor-jackson:$ktor_version") 依赖声明用于 服务器 。您需要为 客户端 声明一个:implementation "io.ktor:ktor-client-jackson:$ktor_version"。您可以找到更多信息 here.