2

我是 Ktor 的新手,我目前正在使用快速启动http api,但我收到错误:

错误应用程序 - 未处理:GET - /snippets com.fasterxml.jackson.databind.JsonMappingException:kotlin.reflect.jvm.internal.KClassImpl 无法转换为 kotlin.reflect.jvm.internal.KClassImpl(通过引用链:java.util. Collections$Singleton Map["snippets"]->java.util.ArrayList[0])

代码:

import com.fasterxml.jackson.databind.SerializationFeature
import io.ktor.application.*
import io.ktor.features.CallLogging
import io.ktor.features.ContentNegotiation
import io.ktor.features.DefaultHeaders
import io.ktor.jackson.jackson
import io.ktor.request.receive
import io.ktor.response.respond
import io.ktor.response.respondText
import io.ktor.routing.Routing
import io.ktor.routing.get
import io.ktor.routing.post
import io.ktor.routing.routing
import java.util.*

data class Snippet(val text: String)

val snippets = Collections.synchronizedList(mutableListOf(
    Snippet("hello"),
    Snippet("world")
))

fun Application.main() {
    install(ContentNegotiation) {
        jackson {
            enable(SerializationFeature.INDENT_OUTPUT)
        }
    }
    routing {
        get("/snippets") {
            call.respond(mapOf("snippets" to synchronized(snippets) { snippets.toList() }))
        }
    }
}

如果我改用这个:

 call.respond(mapOf("snippets" to synchronized(snippets) { snippets.toString() }))

它返回:

   {
  "snippets" : "[Snippet(text=hello), Snippet(text=world)]"
   }

但现在它使用的是 toString() 而不是 toList(),知道如何让它像使用 toList() 的快速入门一样工作吗?

4

1 回答 1

1

发现问题。

使用 application.conf 文件中的 watch 选项来运行服务器似乎搞砸了一些事情。

应用程序.conf 文件:

ktor {
    deployment {
        port = 8080
        watch = [ / ]
    }

    application {
        modules = [ com.MainKt.main ]
    }
}

去除

      watch = [ / ]

或切换回嵌入式服务器似乎已经解决了这个问题。

fun main() {
    embeddedServer(Netty, 8080) {

         //rest of the code

    }.start(wait = true)
}
于 2018-11-22T15:07:58.310 回答