Search code examples
scalascala-collectionssprayspray-json

spray Collection ToResponseMarshallable


I am trying to return a List from my complete directive in spray-routing.

complete {
  List("hello")
}

However, I am getting an error -

Expression of type List[String] doesn't conform to expected type ToResponseMarshallable

I am getting the same error with Seq. I see that marshallers for List and Seq are not provided by default in spray-httpx documentation. However, spray-json provides marshalling support in its DefaultJsonProtocol. I have imported spray.httpx.SprayJsonSupport._ and spray.json.DefaultJsonProtocol._ in my code, but that too hasn't helped.

Any idea how can I marshal a List/Seq using spray-json? Or will I have to write my own Marshaller?

(My scala version is 2.11.4)


Solution

  • Using spray 1.3.2 and spray-json 1.3.2 it should be possible.

    Make sure you import (although you say you do, but double check).

    import spray.httpx.SprayJsonSupport._
    import spray.json.DefaultJsonProtocol._
    

    Consider following example:

    import akka.actor.{ActorSystem, Props, Actor}
    import akka.io.IO
    import spray.can.Http
    import spray.routing.HttpService
    import akka.pattern.ask
    import akka.util.Timeout
    import scala.concurrent.duration._
    import spray.httpx.SprayJsonSupport._
    import spray.json.DefaultJsonProtocol._
    
    object Boot extends App {
      implicit val system = ActorSystem("so")
    
      val testActor = system.actorOf(Props[TestActor])
    
      implicit val timeout = Timeout(5.seconds)
      IO(Http) ? Http.Bind(testActor, interface = "0.0.0.0", port = 5000)
    
    }
    
    class TestActor extends Actor with HttpService {
    
      def receive  = runRoute(route)
    
      def actorRefFactory = context
    
      val route = get{
        path("ping") {
          complete(List("OK"))
        }
      }
    
    }
    

    Requesting /ping returns ["OK"] which looks okay.

    Just for reference build.sbt bellow.

    build.sbt

    val akkaVersion = "2.3.5"
    
    val sprayVersion = "1.3.2"
    
    resolvers += "spray" at "http://repo.spray.io/"
    
    scalaVersion := "2.11.5"
    
    scalacOptions := Seq("-feature", "-unchecked", "-deprecation", "-encoding", "utf8")
    
    libraryDependencies ++= Seq(
      "com.typesafe.akka"   %% "akka-actor"       % akkaVersion,
      "io.spray"            %% "spray-can"        % sprayVersion,
      "io.spray"            %% "spray-routing"    % sprayVersion,
      "io.spray"            %% "spray-client"     % sprayVersion,
      "io.spray"            %% "spray-json"       % "1.3.1"
    )