JSON 请求正文使用 KTOR 转义

JSON Request Body is escaped with KTOR

我正在创建一个带有简单 JSON 正文的 POST 请求。当我像这样创建 JSON 字符串时:

Json.encodeToString(NewAlias(my_id= "j-mueller", alias_name= "finny"))

然后打印出来,看起来像这样:

{"my_id":"j-mueller","alias_name":"finny"}

然后,当我像这样使用 KTOR 尝试 post 它到我的端点时:

val response = httpClient.post<String>("https://myurl/als/create") {
                        contentType(ContentType.Application.Json)
                        body = Json.encodeToString(NewAlias(my_id= "j-mueller", alias_name= "finny"))

                    }

在日志中我看到 Ktor 似乎对内容进行了转义,看起来像这样:

"{\"my_id\":\"j-mueller\",\"alias_name\":\"finny\"}"

我收到“400 - 错误请求”作为响应。我对这种行为有影响吗?还是只是添加了“”的ktor-logger?当我通过 postman 在主体中没有“/”的情况下尝试 post 时,它起作用了,所以我认为这就是问题所在...

有什么想法吗?

谢谢, 詹斯

要么使用 JsonFeature 让 Ktor 序列化一个主体:

val client = HttpClient(CIO) {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
}

val response = client.post<String>("http://httpbin.org/post") {
    contentType(ContentType.Application.Json)
    body = NewAlias(my_id= "j-mueller", alias_name= "funny") // Do not serialize explicitly here
} 

或者显式序列化请求主体但不要使用 JsonFeature:

val client = HttpClient(CIO)

val response = client.post<String>("http://httpbin.org/post") {
    contentType(ContentType.Application.Json)
    body = Json.encodeToString(NewAlias(my_id= "j-mueller", alias_name= "finny"))
}