Stepping into JSON Arrays in Play Framework

帅比萌擦擦* 提交于 2020-02-28 00:34:03

问题


I am trying to parse through some json in the play framework from a remote http response. I am trying to get into results[0]->locations[0]->latLng->lat. I am using playframework 2.0 with scala.

Below is the code I am using with a few commented examples of what i've tried so far.

  val promise = WS.url("http://www.mapquestapi.com/geocoding/v2/address?...").get()
  val body = promise.value.get.body
  val json = Json.parse(body)
  val maybeLat = (json \ "results" \ "0" \ "locations" \ "0" \ "latLng" \ "lat").asInstanceOf[String]
  //val maybeLat = (json \ "results[0]" \ "locations[0]" \ "latLng" \ "lat").asInstanceOf[String]
  //val maybeLat = (json \ "results(0) \ "locations(0) \ "latLng" \ "lat").asInstanceOf[String]

  Ok(body).withHeaders(CONTENT_TYPE -> "text/json")

Errors I'm getting from play framework: http://pastebin.com/S5S3nY5D JSON That i'm trying to parse: http://pastebin.com/7rfD0j2n


回答1:


I think a much better way would be:

val resultsArray = (json \ "results").as[JsArray]
val locations = resultsArray \\ "locations"

at this point, locations will be a list of objects that you can traverse, without having to access them manually through their index.




回答2:


Try this, ordinal access must be after the path traversing.

val result = (json \ "results")(0)
val location = (result \ "locations")(0)
val lat = (location \ "latLng" \ "lat")

With this, you can build your one-line solution:

(((json \ "results")(0) \ "locations")(0) \ "latLng" \ "lat")


来源:https://stackoverflow.com/questions/13960900/stepping-into-json-arrays-in-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!