7

我正在尝试重新处理这个这个,但我不断收到一个我无法修复的错误......

首先,这是我的依赖项:

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'

现在我想做的是:

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

和:

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

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

现在我得到这个错误:

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

我尝试了很多东西,但无法让它发挥作用。我试过了

Answer(1, "test").toJson
Answer(1, "test").toJson.asJsObject

最后我所做的是

complete {
    Answer(1, "test").toJson.compactPrint
}

这可行,但是当我需要 application/json 时,它会作为 Content-Type: text/plain 发送给客户端。

有人看到这里有什么问题吗?

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

4

3 回答 3

4

将您的模型移到 json 协议之外并使其成为常规对象(而不是案例对象)

case class Answer(code: Int, content: String)

object MasterJsonProtocol extends DefaultJsonProtocol {
  implicit val anwserFormat = jsonFormat2(Answer)
}

编辑

还要清理你的导入:

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 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)
}
于 2014-07-11T19:25:49.547 回答
2

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

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

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

于 2014-07-11T21:13:29.113 回答
0

在我的情况下,无法解析的隐式格式实例的名称与本地定义冲突,因此它被遮蔽了。编译器对此保持沉默。经过数小时的头部撞击后才偶然发现。

于 2016-10-21T12:26:10.657 回答