【scala】Json与Scala类型的相互转换处理

1、头文件

import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import net.minidev.json.parser.JSONParser
import scala.collection.JavaConversions.mapAsScalaMap
import scala.collection.mutable
import java.util

2、 String转成JSONArray

  def getArrayFromJson(jsonStr: String) = {
    JSON.parseArray(jsonStr)
  }

3、String转成JSONObject

def getObjectFromJson(jsonStr: String): JSONObject = {
    JSON.parseObject(jsonStr)
  }

4、配合getObjectFromJson 使用把 JSONObject 变为 map

  def jsonObj2Map(jsonObj:JSONObject): mutable.Map[String, String] = {
    var map = mutable.Map[String, String]()
    val itr: util.Iterator[String] = jsonObj.keySet().iterator()
    while (itr.hasNext) {
      val key = itr.next()
      map += ((key, jsonObj.getString(key)))
    }
    map
  }

5、json 字符串转成 Map

  def json2Map(json: String): mutable.HashMap[String,String] ={
    val map : mutable.HashMap[String,String]= mutable.HashMap()
    val jsonParser =new JSONParser()
    //将string转化为jsonObject
    val jsonObj: JSONObject = jsonParser.parse(json).asInstanceOf[JSONObject]

    //获取所有键
    val jsonKey = jsonObj.keySet()

    val iter = jsonKey.iterator()

    while (iter.hasNext){
      val field = iter.next()
      val value = jsonObj.get(field).toString

      if(value.startsWith("{")&&value.endsWith("}")){
        val value = mapAsScalaMap(jsonObj.get(field).asInstanceOf[util.HashMap[String, String]])
        map.put(field,value.toString())
      }else{
        map.put(field,value)
      }
    }
    map
  }

6、map转成json字符:

  def map2Json(map : mutable.Map[String,String]): String = {
    import net.minidev.json.{JSONObject}
    import scala.collection.JavaConversions.mutableMapAsJavaMap
    val jsonString = JSONObject.toJSONString(map)
    jsonString
  }
}

7、jsonstr转化为array:

例子:
读取mysql 中json字段如:’[“蔻露薇”, “COCOVEL”]'转成scala array

  def strConvertArray(jsonstr:String): Array= {
    var modleArray:Array[String] = Array()
    val aliasJson = JSON.parseArray(jsonstr)
    val aliastArray = aliasJson.toArray(modleArray)
    aliastArray 
  }

你可能感兴趣的:(scala)