Search code examples
scalasprayspray-json

Marshalling list of case class objects


I want to return list of json objects based on my case class objects.

Following is my spray router, which returns list of 'Appointment' objects.

trait GatewayService extends HttpService with SLF4JLogging {

  import com.sml.apigw.protocols.AppointmentProtocol._
  import spray.httpx.SprayJsonSupport._

  implicit def executionContext = actorRefFactory.dispatcher

  val router =
    pathPrefix("api" / "v1") {
      path("appointments") {
        get {
          complete {
            val a = new Appointment("1", "2")
            val l = List(a, a, a, a)
            l
          }
        }
      }
    }
  }
}

Following is the 'AppointmentProtocol'

import spray.json.DefaultJsonProtocol

case class Appointment(id: String, patient: String)

object AppointmentProtocol extends DefaultJsonProtocol {
  implicit val appointmentFormat = jsonFormat2(Appointment.apply)
}

It gives the compilation error 'expression type of List[Appointment] doesn't confirms to expected type toResponseMarshallable'


Solution

  • Maybe you missed something in your example, but my brain-based compiler is telling me that your code should throw a compilation error since any directive in Spray requires a result of type Route, as i can see you have a List[Appointment]. Please read this article on Routes. Your route structure should be completed with complete, so i assume the this way would solve your issue:

    get {
      val a = new Appointment("1", "2")
      val l = List(a, a, a, a)
      complete(l)
    }
    

    Please note a complete directive which wraps the list. This should help, otherwise please provide the tree with resolved implicits by compiling your code with the flag -Xprint:typer, that should show where the problem with implicits is.