在scala \ Play中解析Json数组响应

时间:2015-12-14 17:13:19

标签: scala playframework

有一个Web服务返回一些东西

{"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")

2 个答案:

答案 0 :(得分:1)

Your value of json is actually a Future[Seq[JsValue]], so when you foreach over the future you get the entire list back. You would need an additional foreach to iterate over the list of values.

答案 1 :(得分: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中,它被视为" Monadic操作的一部分"这对我来说仍然是一个灰色区域:),但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]