访问Scala中的内部JSON字段

时间:2015-07-07 22:24:48

标签: json scala json4s

我有JSON字符串

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

我正在尝试使用notificationCount中的json4s获取Scala字段,但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")
}

1 个答案:

答案 0 :(得分:0)

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

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]
  ...
}