scala 递归解析fastjson

scala 递归解析fastjson



import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}

import scala.collection.mutable

/**
 * @Auther xxxx
 * @Date 2020-10-30 1:38 下午 
 */

object JsonUtil {

  def analysis(jsonObject: JSONObject): mutable.HashMap[String, AnyRef] = {
    val emptyMap = new mutable.HashMap[String, AnyRef]()
    val keySet = jsonObject.keySet()

    val keyIterator = keySet.iterator()

    while (keyIterator.hasNext()) {
      val keyNext = keyIterator.next()
      val value = jsonObject.get(keyNext)

      if (value.isInstanceOf[JSONObject]) {
        emptyMap ++= analysis(value.asInstanceOf[JSONObject])
      } else if (value.isInstanceOf[JSONArray]) {
        val jsonArray = value.asInstanceOf[JSONArray]
        if (jsonArray.size() > 0) {
          if (jsonArray.get(0).isInstanceOf[JSONArray] || jsonArray.get(0).isInstanceOf[JSONObject]) {
            analysisJSONArray(jsonArray, emptyMap)
          } else {
            emptyMap.put(keyNext, value)
          }
        }else{
          emptyMap.put(keyNext, value)
        }
      } else {
        emptyMap.put(keyNext, value)
      }
    }
    emptyMap
  }


  def analysisJSONArray(jsonArray: JSONArray, emptyMap: mutable.HashMap[String, AnyRef]) {
    val jsonIterator = jsonArray.iterator()
    while (jsonIterator.hasNext()) {
      val  jsonAnyRef = jsonIterator.next()
      if (jsonAnyRef.isInstanceOf[JSONObject]) {

        emptyMap ++= analysis(jsonAnyRef.asInstanceOf[JSONObject])

      } else if (jsonAnyRef.isInstanceOf[JSONArray]) {
        val array: JSONArray = jsonAnyRef.asInstanceOf[JSONArray]
        if (array.size() > 0) {
          analysisJSONArray(array, emptyMap)
        }
      }
    }
  }


  def jsonStr() = {




      """
        |{ "aaaa":[],
        |    "neGpsBean":{
        |        "gpsInformationType":5,
        |        "latitude":30825744,
        |        "locationCode":0,
        |        "locations":[
        |            "有效定位",
        |            "北纬",
        |            "东经"
        |        ],
        |        "longitude":115369776
        |    },
        |    "insulationResistance":4255
        |
        |}
        |""".stripMargin
  }

  def main(args: Array[String]): Unit = {


    val jsonObject = JSON.parseObject(jsonStr())

    //递归解析json
    val stringToObject = analysis(jsonObject)

    for ((key, value) <- stringToObject) {
      println("key  :" + key + "  value  :" + value)
    }


  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值