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)
}
}
}