如何添加Kotlin对Google Java Cloud Endpoints的支持

时间:2018-09-07 00:36:33

标签: google-app-engine kotlin google-cloud-endpoints google-cloud-endpoints-v2

我正在尝试将Kotlin用于Google Java Cloud Endpoints,但是我遇到了以下反序列化Kotlin数据类的异常

INFO: exception occurred while calling backend method
com.google.api.server.spi.response.BadRequestException: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of my.package.Foo: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
 at [Source: UNKNOWN; line: -1, column: -1]
        at com.google.api.server.spi.request.RestServletRequestParamReader.read(RestServletRequestParamReader.java:128)
        at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:349)
        at com.google.api.server.spi.handlers.EndpointsMethodHandler$RestHandler.handle(EndpointsMethodHandler.java:119)
        at com.google.api.server.spi.handlers.EndpointsMethodHandler$RestHandler.handle(EndpointsMethodHandler.java:102)
        at com.google.api.server.spi.dispatcher.PathDispatcher.dispatch(PathDispatcher.java:50)
        at com.google.api.server.spi.EndpointsServlet.service(EndpointsServlet.java:71)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        ...

我的Kotlin文件...

 // file: Foo.kt

 data class Foo(val bar: String) {
 }


 // file: MyEndpoint.kt

 // My GET works fine as Serialization Does work
 @ApiMethod(name = "getFoo",
         description = "testing get",
         path = "getFoo",
         httpMethod = ApiMethod.HttpMethod.GET)
 fun getFoo(): Foo {
     val myFoo = Foo("myBar")
     return myFoo
 }

 // My Post doesn't work, de-serialization is broken
 @ApiMethod(name = "postFoo",
         description = "testing post",
         path = "postFoo",
         httpMethod = ApiMethod.HttpMethod.POST)
 fun postFoo(myFoo: Foo): Foo {
     val postFoo = Foo(myFoo.bar)
     return postFoo
 }

我看到我需要将KotlinModule添加到Jackson ObjectMapper

 // file: build.gradle    
 compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.8.4")

 // adding this will fix the problem, but Where??
 objectMapper.registerModule(new KotlinModule());

在哪里可以为Java端点操纵“全局” ObjectMapper?

我看到我可以在@Api或数据类本身中添加一个Transformer。 如果我将其添加到@Api,我似乎没有得到任何类型信息,所以就可以了

将其添加到数据类需要我为每个数据类制作另一个Transformer。哪一个 似乎可以,但是增加了很多麻烦。

是否存在用于设置/修改默认ObjectMapper的优雅解决方案?

0 个答案:

没有答案