使用Either解析失败和成功

时间:2016-02-04 19:56:07

标签: scala spray-json

我正在尝试使用喷雾合并Github拉取请求。 Github's API将返回不同的值,具体取决于它是成功还是失败。

如何将其解析为Either

使用以下导入:

import akka.actor.ActorSystem
import spray.client.pipelining._
import spray.json._
import scala.concurrent.Future

他们的协议如下:

object GithubWebProtocol extends DefaultJsonProtocol {
  case class MergeSuccess(message:String, merged:Boolean, sha:String)
  case class MergeFailure(message:String, documentation_url:String)
  implicit val mergeSuccessFormat = jsonFormat3(MergeSuccess)
  implicit val mergeFailureFormat = jsonFormat2(MergeFailure)
}

然后,如果我有一个看起来像这样的应用程序:

object GithubWebAPITester extends App {
  implicit val system = ActorSystem()
  import system.dispatcher
  import GithubWebProtocol._

  val api = "https://api.github.com/v3"

  case class PullRequest(org:String, proj:String, pr:Int)

  val mergePullRequest:PullRequest => Future[Either[MergeFailure, MergeSuccess]] = pr => {
    val req = Post(s"$api/repos/${pr.org}/${pr.proj}/pulls/${pr.pr}/merge")
    val pipeline = addHeader("Authorization", s"token ${sys.env("GITHUB_TOKEN")}") ~>
      sendReceive ~>
      unmarshal[Either[MergeFailure, MergeSuccess]]
    pipeline(req)
  }

  mergePullRequest(PullRequest("dvmlls", "slakka-bot", 15)).onComplete {
    case a:Any =>
      println(a)
      system.terminate()
      sys.exit()
  }
}

我收到以下编译错误:

[error] ./src/main/scala/GithubWebAPI.scala:27: could not find implicit value for evidence parameter of type spray.httpx.unmarshalling.FromResponseUnmarshaller[Either[GithubWebProtocol.MergeFailure,GithubWebProtocol.MergeSuccess]]
[error]       unmarshal[Either[MergeFailure, MergeSuccess]]
[error]                ^

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

解决了这个问题,有两个问题:

  1. IntelliJ错误地建议我删除以下行,这是必需的:
  2. import spray.httpx.SprayJsonSupport._

    1. 根据此评论需要添加rootEitherFormathttps://stackoverflow.com/a/25417819/908042
    2. 这两者的结合是杀人'我。

      此处的工作代码:https://github.com/dvmlls/slakka-bot/commit/b7aacdf506c36eb5244d6f1bdd1a707c47aaf5c2