Spray不会将我的case类转换为json并期望一个spray.httpx.marshalling.ToResponseMarshallable

yde*_*ino 7 scala spray spray-json

我正试图重复这个这个,但我一直得到一个错误,我无法解决...

首先,这是我的依赖:

compile 'io.spray:spray-can_2.11:1.3.1'
compile 'io.spray:spray-routing_2.11:1.3.1',
compile 'io.spray:spray-json_2.11:1.2.6'
Run Code Online (Sandbox Code Playgroud)

现在我要做的是:

class WHttpService extends Actor with HttpService with ActorLogging {

  implicit def actorRefFactory = context

  def receive = runRoute(route)

  lazy val route = logRequest(showReq _) {
    // Way too much imports but I tried all I could find
    import spray.json._
    import DefaultJsonProtocol._
    import MasterJsonProtocol._
    import spray.httpx.SprayJsonSupport._
    path("server" / Segment / DoubleNumber / DoubleNumber) { (login, first, second) =>
      get {
          complete {
            Answer(1, "test")
          }
      }
    }
  }

  private def showReq(req : HttpRequest) = LogEntry(req.uri, InfoLevel)
}
Run Code Online (Sandbox Code Playgroud)

附:

case object MasterJsonProtocol extends DefaultJsonProtocol with SprayJsonSupport {
  import spray.json._

  case class Answer(code: Int, content: String)
  implicit val anwserFormat: JsonFormat[Answer] = jsonFormat2(Answer)
}
Run Code Online (Sandbox Code Playgroud)

现在我收到这个错误:

Error:(42, 19) type mismatch;
 found   : MasterJsonProtocol.Answer
 required: spray.httpx.marshalling.ToResponseMarshallable
            Answer(1, "test")
                  ^
Run Code Online (Sandbox Code Playgroud)

我尝试了很多东西,但却无法使它成功.我试过了

Answer(1, "test").toJson
Answer(1, "test").toJson.asJsObject
Run Code Online (Sandbox Code Playgroud)

最后我做的是

complete {
    Answer(1, "test").toJson.compactPrint
}
Run Code Online (Sandbox Code Playgroud)

这有效,但当我需要application/json时,它会以Content-Type:text/plain的形式发送给客户端.

有人看到这里的问题是什么?

编辑:我在github上添加了一个示例项目https://github.com/ydemartino/spray-test

Gan*_*ead 2

我创建了一个拉取请求来解决您的问题:https ://github.com/ydemartino/spray-test/pull/1

必须先声明 json 协议对象,然后才能隐式使用它。我不完全确定为什么编译器无法弄清楚它,但是将对象声明移到顶部修复了它。

对于您的实际项目,请确保在每个文件中声明包,然后在导入语句中使用这些包。