加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – Spray不会将我的case类转换为json并期望一个spray.http

发布时间:2020-12-16 19:17:57 所属栏目:安全 来源:网络整理
导读:我正在尝试重新发布 this或 this,但我一直收到错误,我无法修复… 首先,这是我的依赖项: 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 WHttpServ
我正在尝试重新发布 this或 this,但我一直收到错误,我无法修复…

首先,这是我的依赖项:

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上添加了一个示例项目

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读