在scala \ Play中解析Json数组响应 [英] Parse Json array response in scala\Play
问题描述
有一个Web服务返回一些东西
There is a web service returning array of something
{"apps": [{"name": "one"}, {"name": "two"}]}
在我的代码中,我想遍历每个名字
In my code I want to iterate every name
val request = WS.url(s"http://localhost:9000/getData")
val json = request.get.map { response =>
(response.json \ "apps" \\ "name")
}
json.foreach(println)
但是我所有的尝试都返回单条记录
However all my attempts return single record
// Expect
one
two
// Actual
ListBuffer("one", "two")
推荐答案
首先,这里的整洁解决方案是:
First of all, the neat solution here would be:
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
开头,依此类推.如果这样做,示例中的问题将更加明显:>
Secondly, if you don't want to get confused about the types, you should change your naming standards. For a Future
object, you may start with the prefix future
, for an Option
, it could start with maybe
, etc. If you do so, the problem in your example will be more obvious:
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中,它被视为单子运算"的一部分,对我来说,这仍然是一个灰色区域:),但是Scala源中对Future.foreach
的注释是这样的:
Thirdly, why would Future
trait have a method called foreach
? I think that's confusing for beginners and even mid-level developers. We know from other languages that, foreach means iterate over a list of objects. In Scala, it is considered part of "Monadic operations" which is still a gray area for me :), but the comment for Future.foreach
in Scala source is this:
/** Asynchronously processes the value in the future once the value becomes available.
*
* Will not be called if the future fails.
*/
def foreach[U]
这篇关于在scala \ Play中解析Json数组响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!