【问题标题】:Accessing inner JSON field in Scala在 Scala 中访问内部 JSON 字段
【发布时间】:2015-07-07 22:24:48
【问题描述】:

我有 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")
}

【问题讨论】:

    标签: json scala json4s


    【解决方案1】:

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

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

    【讨论】:

    • 我想在 Map for 循环中做。不在 getData() 中。
    • 在遍历树时最好保留 JSON AST(或树),以便您可以使用子树进行路径。查看更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2019-09-18
    • 2013-10-21
    • 1970-01-01
    • 2018-10-31
    相关资源
    最近更新 更多