Scala调度GET请求,无法解析对json的响应

Nim*_*007 6 parsing json scala databinder scala-dispatch

我写的功能:

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)
Run Code Online (Sandbox Code Playgroud)

问题是在此之后,myJsonNone,而我期望它保留响应中的json数据.

救命 ?

Tra*_*own 16

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)
}
Run Code Online (Sandbox Code Playgroud)

这个例子使用了Json4s库,并为Lift JSON提供了类似的支持(但遗憾的是没有Argonaut,尽管自己编写这样的东西并不太难).

  • `"net.databinder.dispatch"%"dispatch-json4s-native_2.11"%"0.11.1"` (6认同)
  • 我总是得到`对象json4s不是包dispatch.as`的成员.编辑:刚刚意识到我必须将依赖项添加到我的build.sbt http://mvnrepository.com/artifact/net.databinder.dispatch/dispatch-json4s-native_2.10/0.11.1 (2认同)
  • @joslinm你会想到更准确地说你添加到build.sbt的内容吗?我有同样的问题,添加依赖但仍然有问题. (2认同)

fla*_*ian 6

这不是一个好主意,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)));
  }
}
Run Code Online (Sandbox Code Playgroud)

默认的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.
Run Code Online (Sandbox Code Playgroud)

  • "OK"意味着"忽略"所有非200响应并不是真的,它会返回一个"未来",这些响应会失败,但这通常正是你想要的.您仍然可以干净地处理非200响应. (2认同)