给定一个像这样的JSON字符串:
{"Locations":
{"list":
[
{"description": "some description", "name": "the name", "id": "dev123"},
{"description": "other description", "name": "other name", "id": "dev59"}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我想从解析上面字符串的函数返回一个"id"列表.JSON.parseFull()(来自scala.util.parsing.json)给我一个类型的结果Option[Any].Scala REPL显示它Some(Map(Locations -> Map(list -> List(Map(id -> dev123, ...和Scala的初学者一样,我对于接近它的方式感到困惑.
Scala API文档建议"将其视为集合或monad并使用map,flatMap,filter或foreach".顶级元素是一个选项[Any]但是应该是一些Map应该包含单个键"Locations"的Map,它应该包含一个最终是List的键"list".Scala编写一个检索"id"的函数的惯用方法是什么?
首先,你应该将json从Any转换为正确的类型:
val json = anyJson.asInstanceOf[Option[Map[String,List[Map[String,String]]]]]
Run Code Online (Sandbox Code Playgroud)
然后你可以使用map方法从Option中提取id :
val ids = json.map(_("Locations")("list").map(_("id"))).getOrElse(List())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9502 次 |
| 最近记录: |