【问题标题】:how to set response with camelCase in finatra如何在finatra中使用camelCase设置响应
【发布时间】:2020-04-28 09:13:15
【问题描述】:

我需要用 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]
    }
}

附:我对 Scala 非常陌生

【问题讨论】:

  • 你不能像那样在终点使用它。您需要将逻辑包装在 TwitterModule 中并将该模块绑定到您的服务器,以便正确注入。总体而言,使用ScalaObjectMapperModule 可能会更容易
  • 能否举个例子。正如我所说,我对 Scala 很陌生,你所说的有很多未知数:)
  • 我需要启动我的一个旧的 finatra 项目以确保我的示例有效,我不想给你我没有验证过的代码。所以你必须等到我回家。同时请熟悉 Finatra 模块。它将澄清所有那些“未知数”twitter.github.io/finatra/user-guide/getting-started/…

标签: scala finagle finatra


【解决方案1】:

从 cmets 跟进

定义一个自定义的 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

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

【讨论】:

  • 非常感谢您的时间和精力。不幸的是,我不明白这应该去哪里。我已经编辑了我的帖子,以包含更多我当前的设置。请让我知道是否需要添加更多信息。谢谢!
  • @chibis CamelCaseModule 可以去任何地方,只要MyServer 可以引用它,第二行jacksonModule 将在MyServer 之前进入configureHttp
  • 用必要的导入更新了答案@chibis
  • 我想我明白了。我把它放在override def jacksonModule: Module = new CamelCaseModulemyServer 类中。必须更改 override val propertyNamingStrategy: PropertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE 以符合我的要求。它有效。谢谢你,非常感谢@sinanspd!!!!今天花了一整天试图弄清楚
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
相关资源
最近更新 更多