scala - 使用来自 JSON 字符串的嵌套映射

标签 scala

给定一个像这样的 JSON 字符串:

{"Locations":
  {"list":
    [
      {"description": "some description", "name": "the name", "id": "dev123"},
      {"description": "other description", "name": "other name", "id": "dev59"}
    ]
  }
}

我想从解析上述字符串的函数返回一个“id”列表。 JSON.parseFull() (来自 scala.util.parsing.json )给我一个 Option[Any] 类型的结果。 Scala REPL 将其显示为 Some(Map(Locations -> Map(list -> List(Map(id -> dev123, ... 并且作为 Scala 的初学者,我对使用哪种方法感到困惑。

Scala API docs 建议“将其视为集合或 monad,并使用 map、flatMap、filter 或 foreach”。顶级元素是一个 Option[Any] ,但是它应该是 Some ,带有一个应该包含单个键“Locations”的 Map,应该包含一个最终是 List 的单个键“list”。在 Scala 中编写检索“id”的函数的惯用方法是什么?

最佳答案

首先,您应该将 json 从 Any 转换为正确的类型:

val json = anyJson.asInstanceOf[Option[Map[String,List[Map[String,String]]]]]

然后你可以使用 map 方法从 Option 中提取 ids:
val ids = json.map(_("Locations")("list").map(_("id"))).getOrElse(List())

关于scala - 使用来自 JSON 字符串的嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7727773/

相关文章:

scala - 如何读取akka-http中的查询参数?

Scala - 明确说明定义 && 和 || 中的短路功能

scala - 如何从 Google Guava 序列化布隆过滤器?

json - 在使用 circe 解码 JSON 对象时捕获未使用的字段

scala - 类型构造函数参数推断

parsing - Scala:解析匹配的 token

scala - 在 Scala Play 应用程序中避免此 java.lang.ClassCastException 错误的正确应用和取消应用方法是什么?

scala - Play2 表单属性,其中包含 - "value - is not a member of Symbol"

scala - 如果Int不能为null,那么null.asInstanceOf [Int]是什么意思?

scala - Snappy-java 解压缩有效数据失败