Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mattroberts297
Created August 2, 2017 19:51
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mattroberts297/c531a4e9e525d6a18cbf8889ab5f3dec to your computer and use it in GitHub Desktop.
Save mattroberts297/c531a4e9e525d6a18cbf8889ab5f3dec to your computer and use it in GitHub Desktop.
Akka HTTP Circe Custom Marshaller and Unmarshaller
import io.circe._
import io.circe.parser._
import io.circe.syntax._
import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.{ContentTypeRange, HttpEntity}
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import scala.concurrent.Future
/**
* To use circe for json marshalling and unmarshalling:
*
* import CirceSupport._
* import io.circe.generic.auto._
*/
object CirceSupport {
private def jsonContentTypes: List[ContentTypeRange] =
List(`application/json`)
implicit final def unmarshaller[A: Decoder]: FromEntityUnmarshaller[A] = {
Unmarshaller.stringUnmarshaller
.forContentTypes(jsonContentTypes: _*)
.flatMap { ctx => mat => json =>
decode[A](json).fold(Future.failed, Future.successful)
}
}
implicit final def marshaller[A: Encoder]: ToEntityMarshaller[A] = {
Marshaller.withFixedContentType(`application/json`) { a =>
HttpEntity(`application/json`, a.asJson.noSpaces)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment