scala怎么用 json4s判断key是否存在
最近碰到一个场景,需要在Scala里面判断json里面是否存在某个key。如果用fastjson,判断key是否存在很简单,直接containsKey即可。但是项目用的是json4s这个库,用法稍微有些不同,特此记录一下。代码如下:
package dev.json import org.json4s.DefaultFormats import org.json4s.JsonDSL._ import org.json4s.jackson.JsonMethods._ object Course2 { implicit val formats = DefaultFormats val key = "key-to-remove" val s = """ |{"@type":{"version":"1.0.2","name":"application-content","data":[]},"key-to-remove":[{"blah":"more blah"}],"@value":[]} |""".stripMargin val obj = parse(s) def main(args: Array[String]): Unit = { containsKey() } def containsKey(): Unit = { if (null != obj) { val key2 = "random key" println(s"key:[$key] exists" , !obj.findField(_._1.equals(key)).isEmpty) println(s"key:[$key2] exists", !obj.findField(_._1.equals(key2)).isEmpty) } } def deleteKey(): Unit = { if (null != obj) { val obj2 = obj.removeField(_._1.equals(key)) val out = compact(render(obj2)) println(out) } } }