Skip to content

Instantly share code, notes, and snippets.

@zygm0nt
Forked from mattroberts297/CirceSupport.scala
Created August 3, 2017 22:42
Show Gist options
  • Save zygm0nt/c388b8a0954813c4338203614e80271b to your computer and use it in GitHub Desktop.
Save zygm0nt/c388b8a0954813c4338203614e80271b 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