Created
December 9, 2015 19:58
-
-
Save rjsen/08cc2998515b5e02662c to your computer and use it in GitHub Desktop.
Circe (un)marshaller for spray
This file contains hidden or 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 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