2017-06-23 151 views
-2

我的JSON字符串無法遍歷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")) 

} 

我試圖訪問 「臨時」,但它投擲錯誤

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

錯誤消息是相當清楚的。將你的'iterator'轉換成一個Scala集合。 http://docs.scala-lang.org/overviews/collections/conversions-between-java-and-scala-collections.html – metaphori

+0

你在使用什麼JSON庫? – erip

回答

0

這裏是我怎麼可能做到這一點使用播放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) 
)