2015-12-14 64 views
0

有一個web服務返回的東西斯卡拉播放解析JSON陣列響應

{"apps": [{"name": "one"}, {"name": "two"}]} 

陣列在我的代碼我想要遍歷每個名​​字

val request = WS.url(s"http://localhost:9000/getData") 

val json = request.get.map { response => 
    (response.json \ "apps" \\ "name") 
} 

json.foreach(println) 

但是我所有的努力回單記錄

// Expect 
one 
two 
// Actual 
ListBuffer("one", "two") 

回答

1

首先,這裏的整潔的解決辦法是:

val request = WS.url(s"http://localhost:9000/getData") 

request.get.map { response => 
    val names = (response.json \ "apps" \\ "name") 
    names.foreach(println) 
} 

其次,如果你不想弄不清楚的類型,你應該改變你的命名標準。對於Future對象,你可以用前綴future開始,爲Option,它可以與maybe啓動等,如果你這樣做,在你的榜樣的問題會更加明顯:

val request = WS.url(s"http://localhost:9000/getData") 

val futureJson = request.get.map { response => 
    (response.json \ "apps" \\ "name") 
} 

futureJson.foreach(println) // you call foreach for a Future, not for a List 

第三,爲什麼Future性狀會有一種叫做foreach的方法嗎?我認爲這對初學者甚至中級開發人員來說都是令人困惑的。我們從其他語言知道,foreach意味着遍歷一系列對象。在Scala中,它被認爲是「一元行動」這仍然是一個灰色地帶,我:)的一部分,但在斯卡拉源Future.foreach的評論是這樣的:

/** Asynchronously processes the value in the future once the value becomes available. 
    * 
    * Will not be called if the future fails. 
    */ 
    def foreach[U] 
+0

謝謝你,爲解決方案,解釋和建議。事實上,我是斯卡拉的初學者。 –

1

你的json值實際上是一個Future[Seq[JsValue]],所以w ^在你未來的時候,你會收到整個名單。您需要額外的foreach才能遍歷值列表。