[英]Scala dispatch GET request, fail to parse response to json
我寫的功能:
1)發送HTTP GET請求(響應是有效的JSON)
2)解析對json對象的響應
代碼段:
val page = url("http://graph.facebook.com/9098498615")
val response = Http(page OK dispatch.as.String)
Await.result(response , 10 seconds)
val myJson= JSON.parseFull(response .toString)
//this isnt helping -> val myJson= JSON.parseRaw(response .toString)
問題是在此之后, myJson為None,而我期望它保留響應中的json數據。
救命 ?
Dispatch包含一些非常好的(並且廣告不足) 用於解析JSON的工具 ,您可以像這樣使用它(請注意,您可以使用任何標准方法處理非200個響應來處理失敗的期貨):
import dispatch._
import org.json4s._, org.json4s.native.JsonMethods._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{ Failure, Success }
val page = url("http://graph.facebook.com/9098498615")
val response = Http(page OK dispatch.as.json4s.Json)
response onComplete {
case Success(json) => println(json \ "likes")
case Failure(error) => println(error)
}
這個例子使用了Json4s庫 ,並為Lift JSON提供了類似的支持(但遺憾的是沒有Argonaut ,盡管自己編寫這樣的東西並不太難)。
使用Http(page OK as.String)
並不是一個好主意,因為所有與HTTP 200不同的響應都會導致Futures失敗。 如果您需要對錯誤處理/報告進行更細粒度的控制,請改為針對特定方案。
import org.jboss.netty.handler.codec.http.{ HttpRequest, HttpResponse, HttpResponseStatus }
def getFacebookGraphData: Either[Exception, String] = {
val page = url("http://graph.facebook.com/9098498615")
val request = Http(page.GET);
val response = Await.result(request, 10 seconds);
(response.getStatusCode: @annotation.switch) match {
case HttpResponseStatus.OK => {
val body = response.getResponseBody() // dispatch adds this method
// if it's not available, then:
val body = new String(response.getContent.array);
Right(body)
}
// If something went wrong, you now have an exception with a message.
case _ => Left(new Exception(new String(response.getContent.array)));
}
}
默認的Scala JSON庫也不是一個好主意,它與其他庫相比非常粗糙。 試試lift-json
。
import net.liftweb.json.{ JSONParser, MappingException, ParseException };
case class FacebookGraphResponse(name: String, id: String);// etc
implicit val formats = net.liftweb.DefaultFormats;
val graphResponse = JSONParser.parse(body).extract[FacebookGraphResponse];
// or the better thing, you can catch Mapping and ParseExceptions.
您還可以使用您自己喜歡的json-library(例如play-framework-json-lib),如下所示:
val response = Http(requestUrl OK CarJsonDeserializer)
你只需要通過JsonDeserializer擴展(Response => Car)特性。
object CarJsonDeserializer extends (Response => Car) {
override def apply(r: Response): Car = {
(dispatch.as.String andThen (jsonString => parse(jsonString)))(r)
}
}
和json-parser:
implicit val carReader: Reads[Car] = (
(JsPath \ "color").read[String] and
(JsPath \ "model").read[String]
)(Monitor.apply _)
private def parse(jsonString: String) = {
val jsonJsValue = Json.parse(jsonString)
jsonJsValue.as[Car]
}
請參閱此博客文章: https : //habashics.wordpress.com/2014/11/28/parsing-json-play-lib-with-dispatch/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.