scalafinaglefinatra

how to set response with camelCase in finatra


I need to return a json response in camelCase with finatra but it is in snake_case by default. From what I found so far, I need to use ObjectMapper, but I can't understand where do I pass it once I create it. An example would be very helpful. Here is what I have:

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]
    }
}

P.S. I am very-very new to Scala


Solution

  • Following up from the comments

    Define a custom 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)
     }
    }
    

    Override the default Jackson module for your server

    override def jacksonModule = new CamelCaseModule
    

    Make sure you have

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

    in your build.sbt

    And that you import

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

    Tested it locally and it seems to work Hope this helps