spray Collection ToResponseMarshallable

ade*_*for 5 scala scala-collections spray spray-json

我试图从喷涂路由中的完整指令返回一个List.

complete {
  List("hello")
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个错误 -

Expression of type List[String] doesn't conform to expected type ToResponseMarshallable
Run Code Online (Sandbox Code Playgroud)

我和Seq有同样的错误.我看到默认情况下不在spray-httpx 文档中提供List和Seq的marshallers .但是,spray-json在其DefaultJsonProtocol中提供了编组支持.我在我的代码中导入了spray.httpx.SprayJsonSupport._和spray.json.DefaultJsonProtocol._,但这也没有帮助.

知道如何使用spray-json编组List/Seq?或者我必须写自己的Marshaller?

(我的scala版本是2.11.4)

lpi*_*ora 5

使用spray1.3.2 和spray-json1.3.2 应该是可能的。

确保您导入(虽然您说您这样做,但请仔细检查)。

import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
Run Code Online (Sandbox Code Playgroud)

考虑以下示例:

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"))
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

要求/ping退货["OK"],看起来不错。

以下仅供参考build.sbt

生成.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"
)
Run Code Online (Sandbox Code Playgroud)

  • 好的。我认为这只是 IntelliJ 疯了。当我构建并运行我的项目时,它工作正常。谢谢! (3认同)