gpt4 book ai didi

scala - Spray 不会将我的案例类转换为 json 并期待一个 spray.httpx.marshalling.ToResponseMarshallable

转载 作者:行者123 更新时间:2023-12-04 12:07:46 27 4
gpt4 key购买 nike

我正在尝试重现 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

最佳答案

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

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

关于scala - Spray 不会将我的案例类转换为 json 并期待一个 spray.httpx.marshalling.ToResponseMarshallable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704749/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com