在 Scala 中访问内部 JSON 字段

Accessing inner JSON field in Scala

我有 JSON 个字符串

{
  "whatsNew" : {
    "oldNotificationClass" : "WhatsNewNotification",
    "notificationEvent" : { ..... },
    "result" : {
      "notificationCount" : 10
      .....
    }
  },
  ......
  "someEmpty": { },
  ......
}

我正在尝试使用 Scala 中的 json4s 获取 notificationCount 字段,如下所示,但 notificationCount 对所有人来说都是空的。有帮助吗?

更新 另外,如果某对是空的,我该如何处理空的情况并继续循环?

函数从文件

返回JSON字符串
def getData(): Map[String, AnyRef] = {
  val jsonString = scala.io.Source.fromInputStream(this.getClass.getResourceAsStream("/sample.json")).getLines.mkString
  val jsonObject = parse( s""" $jsonString """)
  jsonObject.values.asInstanceOf[Map[String, AnyRef]]
}

获取字段的代码

val myMap: Map[String, AnyRef] = MyDataLoader.getData

for((key, value) <- myMap) {
  val id = key
  val eventJsonStr: String = write(value.asInstanceOf[Map[String, String]] get "notificationEvent")
  val resultJsonStr: String = write(value.asInstanceOf[Map[String, String]] get "result")
  //val notificationCount: String = write(value.asInstanceOf[Map[String, Map[String, String]]] get "notificationCount")
}

您可以像这样使用路径和提取:

val count: Int = (parse(jsonString) \ "whatsNew" \ "result" \ "notificationCount").extract[Int]

您需要此导入才能使 .extract[Int] 正常工作:

implicit val formats = DefaultFormats

循环执行:

parse(jsonString).children.map { child =>
  val count: Int = (child \ "result" \ "notificationCount").extract[Int]
  ...
}