Scala 将JSON转换成Map

import net.minidev.json.parser.JSONParser
import net.minidev.json.JSONObject
import scala.collection.mutable
import scala.collection.JavaConversions.mapAsScalaMap
import scala.collection.JavaConversions.mutableMapAsJavaMap
def jsonToMap(svdInfo: String) = {
    val parserJson = new JSONParser()
    val jsonObj: JSONObject = parserJson.parse(svdInfo).asInstanceOf[JSONObject]
    /* val tagName = jsonObj.get("tagName").toString
     println("tagName===:" + tagName)*/
    val jsonKey = jsonObj.keySet()
    val iter = jsonKey.iterator()
    val map: mutable.HashMap[String, String] = new mutable.HashMap[String, String]()
    while (iter.hasNext) {
      val instance = iter.next()
      val value = jsonObj.get(instance).toString
      //   map += (instance -> value)
      map.put(instance, value)
      println("===key====:" + instance + "===value===:" + value)
    }
    map
  }

  def jsonToMap1(svdInfo: String) = {
    val parserJson = new JSONParser()
    val jsonObj: JSONObject = parserJson.parse(svdInfo).asInstanceOf[JSONObject]
    /* val tagName = jsonObj.get("tagName").toString
     println("tagName===:" + tagName)*/
    val jsonKey = jsonObj.keySet()
    val iter = jsonKey.iterator()
    val map: mutable.HashMap[String, Object] = new mutable.HashMap[String, Object]()
    while (iter.hasNext) {
      val instance = iter.next()
      val value = jsonObj.get(instance).toString
      if (value.startsWith("{") && value.endsWith("}")) {
        val value = mapAsScalaMap(jsonObj.get(instance).asInstanceOf[mutable.HashMap[String, String]])
        map.put(instance, value)
      } else map += (instance -> value)
      // println("===key====:" + instance + "===value===:" + value)
    }
    map
  }

  //获取Option里的数据
  def show(x: Option[Object]): Object = x match {
    case Some(s) => s
    case None => ""
  }



猜你喜欢

转载自blog.csdn.net/qq_34400736/article/details/81061994