最近碰到一个场景,需要在Scala里面判断json里面是否存在某个key。如果用fastjson,判断key是否存在很简单,直接containsKey即可。但是项目用的是json4s这个库,用法稍微有些不同,特此记录一下。代码如下:
package dev.jsonimport org.json4s.DefaultFormatsimport org.json4s.JsonDSL._import org.json4s.jackson.JsonMethods._object Course2 {implicit val formats = DefaultFormatsval key = \"key-to-remove\"val s =\"\"\"|{\"@type\":{\"version\":\"1.0.2\",\"name\":\"application-content\",\"data\":[]},\"key-to-remove\":[{\"blah\":\"more blah\"}],\"@value\":[]}|\"\"\".stripMarginval 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)}}}