Skip to content

Instantly share code, notes, and snippets.

@lazyvalue
Created July 10, 2015 01:12
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 lazyvalue/906c981e0ac3df470981 to your computer and use it in GitHub Desktop.
Save lazyvalue/906c981e0ac3df470981 to your computer and use it in GitHub Desktop.
argonaut json support for akka-http
import akka.http.scaladsl.marshalling.{ ToEntityMarshaller, Marshaller }
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets}
import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, Unmarshaller }
import akka.stream.FlowMaterializer
import akka.http.scaladsl.model.MediaTypes.`application/json`
import argonaut.{Parse, DecodeJson, EncodeJson, Json}
object ArgonautJsonSupport {
implicit def argonautJsonUnmarshallerConverter[T](decode: DecodeJson[T])(implicit mat: FlowMaterializer): FromEntityUnmarshaller[T] =
argonautJsonObjUnmarshaller(decode, mat)
implicit def argonautJsonObjUnmarshaller[T](implicit decode: DecodeJson[T], mat: FlowMaterializer): FromEntityUnmarshaller[T] =
argonautJsonUnmarshaller.map(decode.decodeJson(_).toOption.get)
implicit def argonautJsonUnmarshaller(implicit mat: FlowMaterializer): FromEntityUnmarshaller[Json] =
Unmarshaller.byteStringUnmarshaller.forContentTypes(`application/json`).mapWithCharset { (data, charset) ⇒
if(charset == HttpCharsets.`UTF-8`) Parse.parseOption(data.utf8String).get
Parse.parseOption(data.decodeString(charset.nioCharset.name)).get
}
implicit def argonautJsonConverter[T](implicit encode: EncodeJson[T]): ToEntityMarshaller[T] =
argonautJsonMarshaller.compose(encode.apply)
implicit def argonautJsonMarshaller[T]: ToEntityMarshaller[Json] =
Marshaller.StringMarshaller.wrap(ContentTypes.`application/json`)(_.nospaces)
}
@briantopping
Copy link

Also check out https://github.com/hseeberger/akka-http-json, which now has Argonaut support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment