user3763116 user3763116 - 1 month ago 6
Scala Question

spray marshalling

I am writing REST api using spray and having some difficulties with json marshalling. My service returns[Failure, Success]. How can I return this data type from the REST endpoint? How to write response marshaller for this?


The simplest solution is just to call toEither on the value in your router, which lets the Spray-provided Either marshaller take over.

Another solution would be to provide your own marshaller (I've done this a couple of times myself):

import spray.httpx.marshalling.ToResponseMarshaller

implicit def xorMarshaller[A, B](implicit
  ma: ToResponseMarshaller[A],
  mb: ToResponseMarshaller[B]
): ToResponseMarshaller[Xor[A, B]] =
  ToResponseMarshaller[Xor[A, B]] { (value, ctx) =>
    value match {
      case Xor.Left(a)  => ma(a, ctx)
      case Xor.Right(b) => mb(b, ctx)

This lets you avoid both the runtime cost (probably negligible) and syntactic cost (less negligible) of converting.

Note that Cats is removing Xor in favor of the standard library's Either in upcoming versions, though, so just going with toEither for now may be the most practical solution.