美文网首页
递归拉平 jsonObject里的数据并且展示成Map

递归拉平 jsonObject里的数据并且展示成Map

作者: 钙世英雄转世 | 来源:发表于2019-05-24 13:50 被阅读0次

    此为scala程序

    def parseJsonByJSONObject(json:JSONObject,fatherKey:String =""):Map[String,String] = {

    val result =new mutable.HashMap[String,String]()

    import scala.collection.JavaConverters._

    val fatherKeys: mutable.Set[String] = json.keySet().asScala

    val resultSet = fatherKeys.map(key =>{

    val value = json.get(key)

    valuematch {

    case value: JSONObject =>

    val map =parseJsonByJSONObject(value,getSonKey(fatherKey,key))

    result ++= map

    case value: JSONArray =>

    val map =parseJsonByJSONArray(value,getSonKey(fatherKey,key))

    result ++= map

    case _ =>

    result.put(getSonKey(fatherKey,key), value.toString)

    }

    })

    result.toMap

    }

    //得到子key

    def getSonKey(fatherKey:String,key:String):String = {

    var sonKey:String =""

      if (fatherKey !="") {

    if (key.startsWith("(") && key.endsWith(")"))

    sonKey = fatherKey + key

    else

          sonKey = fatherKey +"." + key

    }

    else

        sonKey = key

    sonKey

    }

    def parseJsonByJSONArray(json:JSONArray,fatherKey:String ="") = {

    val result =new mutable.HashMap[String,String]()

    val resultSet =new ListBuffer[AnyRef]()

    for (a <-0 until json.length()){

    resultSet.append(json.get(a))

    }

    var count:Int = -1

      resultSet.foreach {case value =>

    count +=1

        valuematch{

    case value: JSONObject =>

    val sonKey =getSonKey(fatherKey,s"(${count})")

    val r:Map[String,String] =parseJsonByJSONObject(value, sonKey)

    result ++= r

    case _ =>throw new Exception("JSONArray内部不是JSONObject类型,不符合规则")

    }

    }

    result.toMap

    }

    示例:

    结果:

    这里面的小括号(0),(1) 等,代表的是 JSONArray的层级结构

    相关文章

      网友评论

          本文标题:递归拉平 jsonObject里的数据并且展示成Map

          本文链接:https://www.haomeiwen.com/subject/vxygzqtx.html