2016-11-20 168 views
0

我想在akka-http中编写一个轮询客户端,将所有响应主体转换为Play JsObject。我到目前为止是编码如下,使用this library这应该使事情变得简单(我认为?)。然而,当我尝试下面我收到以下错误运行该代码:在akka-http客户端中使用PlayJson

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

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