Scala traverses and prints all Keys and Values of com.alibaba.fastjson.JSONObject

In Scala, JSON data can be processed using the Fastjson library. To traverse and print all the Keys and Values ​​of the JSONObject in Fastjson, you can traverse recursively and use the getOrDefault method to output the key-value pairs one by one.
code show as below,:

import com.alibaba.fastjson.JSONObject

object Main extends App {
    
    
  val jsonString =
    """
      |{
      |  "name": "Tom",
      |  "age": 28,
      |  "sex": "male",
      |  "address": {
      |    "province": "Beijing",
      |    "city": "Haidian"
      |  }
      |}
      |""".stripMargin // 定义JSON字符串

  val json = JSONObject.parseObject(jsonString) // 将字符串解析为JSON对象
  printJson(json)

  // 递归遍历JSONObject并输出其中的键值对
  def printJson(json: JSONObject): Unit = {
    
    
    import scala.collection.JavaConverters._
    json.entrySet.asScala.foreach((entry) => {
    
     // 转换Map.Entry为Scala中的Tuple2,并调用foreach方法逐一遍历map中的键值对
      print(entry.getKey + ":") // 输出key
      print(entry.getValue.toString) // 输出value
      println()
      entry.getValue match {
    
     // 对于嵌套的JSONObject或JSONArray,需要递归调用printJson函数来输出其中的键值对
        case obj: JSONObject =>
          printJson(obj)
        case _ =>
      }
    })
  }
}

Note that when recursively traversing the JSONObject, you need to use match to match the value of the JSONObject type, and call the asScala method to convert the Java collection in the JSONObject to a Scala collection. Also be careful with handling nested JSONObject and other types of values.

Guess you like

Origin blog.csdn.net/programmer589/article/details/130297597