我想在akka-http中编写一个轮询客户端,将所有响应主体转换为Play JsObject。到目前为止我所使用的是使用this library的代码,它应该简单(我认为?)。但是当我尝试运行下面的代码时,我收到以下错误:
Error:(26, 56) type mismatch;
found : akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller[play.api.libs.json.JsObject]
(which expands to) akka.http.scaladsl.unmarshalling.Unmarshaller[akka.http.scaladsl.model.HttpEntity,play.api.libs.json.JsObject]
required: akka.http.scaladsl.unmarshalling.Unmarshaller[akka.http.scaladsl.model.HttpResponse,play.api.libs.json.JsObject]
Unmarshaller.byteStringUnmarshaller.mapWithCharset { (data, charset) =>
我需要做些什么才能让事情按预期运作?
import java.util.UUID
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpEntity, HttpRequest, HttpResponse}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.http.scaladsl.unmarshalling.{Unmarshal, Unmarshaller}
import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport._
import play.api.libs.json.{JsObject, Json}
import scala.concurrent.duration._
import scala.util.{Success, Try}
object Main extends App {
implicit val system = ActorSystem("TestSys")
implicit val ec = system.dispatcher
implicit val materializer = ActorMaterializer()
implicit val um:Unmarshaller[HttpResponse, JsObject] = {
Unmarshaller.byteStringUnmarshaller.mapWithCharset { (data, charset) =>
Json.parse(data.toArray).as[JsObject]
}
}
val request = HttpRequest(uri="https://www.google.com/finance/info?q=INDEXDB%3ADAX") -> UUID.randomUUID()
val pool = Http().superPool[UUID]()
val googleFinanceFlow =
Source.tick(0 milliseconds,10000 milliseconds,request)
.via(pool)
.runForeach {
case (Success(response),_) =>
val json = Unmarshal(response).to[JsObject]
println(json.onSuccess{case r => println(r.toString())})
case _ => Json.obj()
}
}
答案 0 :(得分:0)
只需删除Unmarshaller[HttpResponse, JsObject]
的显式隐式(哇,听起来不错,嗯?)定义。这不是必需的,因为PlayJsonSupport
提供了合适的unmarshaller。