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

时间:2014-07-11 19:03:44

标签: scala spray spray-json

我正在尝试重新定位thisthis,但我一直收到错误,我无法修复...

首先,这是我的依赖项:

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

3 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:0)

在我的例子中,不可解析的隐式格式实例的名称与本地定义冲突,因此它被遮蔽了。编译器对此非常缄默。只是在经过几个小时的撞击之后才意外发现。