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)
问题是在此之后,myJson为None,而我期望它保留响应中的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,尽管自己编写这样的东西并不太难).
这不是一个好主意,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)