-
-
Save zygm0nt/c388b8a0954813c4338203614e80271b to your computer and use it in GitHub Desktop.
Akka HTTP Circe Custom Marshaller and Unmarshaller
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 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