Created
November 19, 2014 02:30
-
-
Save chadselph/8d87c365da8a3c97ebf2 to your computer and use it in GitHub Desktop.
Spray JSON Support with Jackson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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