无法迭代json对象

时间:2017-06-23 17:01:07

标签: json scala

我的json字符串

{"list":[{"dt":1498240800,"main":{"temp":295.66,"temp_min":295.66,"temp_max":297.247,"pressure":958.79}},{"dt":1498251600,"main":{"temp":295.23,"temp_min":295.23,"temp_max":296.418,"pressure":957.19}}]}

或者,非常印刷,

{
  "list": [
    {
      "dt": 1498240800,
      "main": {
        "temp": 295.66,
        "temp_min": 295.66,
        "temp_max": 297.247,
        "pressure": 958.79
      }
    },
    {
      "dt": 1498251600,
      "main": {
        "temp": 295.23,
        "temp_min": 295.23,
        "temp_max": 296.418,
        "pressure": 957.19
      }
    }
  ]
}

我的代码

val co = values.get("list").getAsJsonArray

val iterator = co.getAsJsonObject.get("main").getAsJsonObject

for (key <- iterator) {
  println(key.get("temp"))

}

我正在尝试访问“temp”,但它正在抛出错误

Error:(24, 26) value foreach is not a member of java.util.Set[String]
    for (key <- iterator) {

1 个答案:

答案 0 :(得分:0)

以下是我使用play-json的方法:

import play.api.libs.json.{JsArray, Json}

val jsonString =
    """
      |{
      |  "list": [
      |    {
      |      "dt": 1498240800,
      |      "main": {
      |        "temp": 295.66,
      |        "temp_min": 295.66,
      |        "temp_max": 297.247,
      |        "pressure": 958.79
      |      }
      |    },
      |    {
      |      "dt": 1498251600,
      |      "main": {
      |        "temp": 295.23,
      |        "temp_min": 295.23,
      |        "temp_max": 296.418,
      |        "pressure": 957.19
      |      }
      |    }
      |  ]
      |}
    """.stripMargin

val json = Json.parse(jsonString)

val jsonList = (json \ "list").get.as[JsArray].value

jsonList.foreach(o =>
  println((o \ "main" \ "temp").get)
)