Skip to content

Instantly share code, notes, and snippets.

@chadselph
Created November 19, 2014 02:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chadselph/8d87c365da8a3c97ebf2 to your computer and use it in GitHub Desktop.
Save chadselph/8d87c365da8a3c97ebf2 to your computer and use it in GitHub Desktop.
Spray JSON Support with Jackson
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import spray.http.{ContentTypes, HttpCharsets, HttpEntity, MediaTypes}
import spray.httpx.marshalling.Marshaller
import spray.httpx.unmarshalling.Unmarshaller
/**
* Use Jackson directly to avoid json4s's dependencies
*/
trait JacksonJsonSupport {
val jacksonModules = Seq(DefaultScalaModule)
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModules(jacksonModules:_*)
implicit def jacksonJsonUnmarshaller[T : Manifest] =
Unmarshaller[T](MediaTypes.`application/json`) {
case x: HttpEntity.NonEmpty =>
val jsonSource = x.asString(defaultCharset = HttpCharsets.`UTF-8`)
mapper.readValue[T](jsonSource)
}
implicit def jacksonJsonMarshaller[T <: AnyRef] =
Marshaller.delegate[T, String](ContentTypes.`application/json`)(mapper.writeValueAsString(_))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment