0

我需要用 finatra 在 camelCase 中返回一个 json 响应,但默认情况下它是在 snake_case 中的。从我目前发现的情况来看,我需要使用 ObjectMapper,但我不明白创建它后我在哪里传递它。一个例子会很有帮助。这是我所拥有的:

import com.twitter.finagle.http.Request
import com.twitter.finatra.http.Controller

class myTargetingController extends Controller {
    val endpoint = "http://....."

    get(s"$endpoint/?") { request: Request =>
        // what do I do with it?
        // val objectMapper = ScalaObjectMapper.builder.camelCaseObjectMapper 
        response.ok.json(myObject)
    }
}

==================================================== =================

import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.finagle.http.{ Request, Response}
import com.twitter.finatra.http.routing.HttpRouter
import com.twitter.finatra.http.{HttpServer}
import com.twitter.finatra.http.filters.CommonFilters
import com.twitter.util.Future

object MyServerApp extends MyServer

class MyServer extends HttpServer {
override protected def configureHttp(router: HttpRouter) {
    router
        .filter[CommonFilters]
        .add[CorsFilter, MyController]
    }
}

PS我对Scala非常陌生

4

1 回答 1

0

从评论跟进

定义自定义 ObjectMapperModule

class CamelCaseModule extends ScalaObjectMapperModule {

    override val propertyNamingStrategy: PropertyNamingStrategy =
      new PropertyNamingStrategy.UpperCamelCaseStrategy

    override def additionalMapperConfiguration(mapper: ObjectMapper): Unit = {
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
 }
}

覆盖服务器的默认 Jackson 模块

override def jacksonModule = new CamelCaseModule

确保你有

"com.twitter" %% "finatra-jackson" % yourFinatraVersion % "test"

在你的build.sbt

你进口的

import com.fasterxml.jackson.databind.{DeserializationFeature, Module, ObjectMapper, PropertyNamingStrategy}
import com.twitter.finatra.jackson.modules.ScalaObjectMapperModule

在本地测试它似乎有效希望这会有所帮助

于 2020-04-28T00:42:57.417 回答