Skip to content

Instantly share code, notes, and snippets.

@rjsen
Created December 9, 2015 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjsen/08cc2998515b5e02662c to your computer and use it in GitHub Desktop.
Save rjsen/08cc2998515b5e02662c to your computer and use it in GitHub Desktop.
Circe (un)marshaller for spray
import java.util.NoSuchElementException
import io.circe._
import spray.httpx.marshalling.Marshaller
import spray.httpx.unmarshalling.Unmarshaller
import spray.http._
// scalastyle:off
// providing return types causes a stack overflow, and the throw is necessary in this case
trait CirceSupport {
implicit def circeUnmarshaller[T: Decoder] = {
Unmarshaller[T](MediaTypes.`application/json`) {
case x: HttpEntity.NonEmpty =>
val json = jawn.parse(x.asString)
try json.flatMap(_.as[T]).toOption.get
catch {
case nsee: NoSuchElementException => throw new IllegalRequestException(StatusCodes.UnprocessableEntity)
}
}
}
implicit def circeMarshaller[T: Encoder] = {
Marshaller.delegate[T, String](ContentTypes.`application/json`) { value =>
implicitly[Encoder[T]].apply(value).noSpaces
}
}
}
// scalastyle:on
object CirceSupport extends CirceSupport
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment