在akka-http客户端中使用PlayJson

问题描述 投票:0回答:1

我想在 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()
    }
}
json scala playframework akka-http
1个回答
1
投票

只需删除

Unmarshaller[HttpResponse, JsObject]
的显式隐式定义(哇,听起来不错,是吗?)。这是不需要的,因为
PlayJsonSupport
提供了合适的解组器。

© www.soinside.com 2019 - 2024. All rights reserved.