Scala中json格式、字符串、map相互轉換

像map同樣的json直接存值:java

import org.json.JSONObjectjson

 

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

val jsonObj :JSONObject= new JSONObject()
jsonObj.put("zxtotal", "1")
jsonObj.put("zxtota1l", "11")
println(jsonObj)
}code

json對象轉換爲json字符串:orm

import org.json4s.{Formats,NoTypeHints}
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write


case class userLableLike(id:String,pos:Float,neg:Float,seg:Double)
  def userLable2Str(data:userLableLike): String ={
    // 須要添加隱式轉換
    implicit val formats:AnyRef with Formats = Serialization.formats(NoTypeHints)
    // 由scala對象轉換爲Json字符串
    val dstr = write(data)
    dstr
  }

val v1 = userLableLike("1",100,100,0.5)
println(userLable2Str(v1))
// "{id: 1, pos: 100, neg: 100, seg: 0.5}"

 

json字符串轉換成map:xml

import scala.util.parsing.json.JSON

// 把json格式的字符串轉換成map格式,(id:String,pos:Float,neg:Float,seg:Double)
  def str2map(vstr:String): collection.immutable.Map[String, Any] ={
    val vSome = JSON.parseFull(vstr)
//    println(vSome,manOf(vSome)) //(Map(id -> 1, pos -> 100.0, neg -> 100.0, seg -> 0.5),Any)
    // 轉換類型
    var vmap = vSome match {
      case Some(map:collection.immutable.Map[String, Any]) => map
    }
//    println(vmap("id"),manOf(vmap)) //(1,scala.collection.immutable.Map[java.lang.String, Any])
    vmap
  }
//注意用可變集合collection.mutable.Map[String, Any] ,行不通

//查看數據類型方法-manOf(data)
  def manOf[T:Manifest](t:T):Manifest[T]=manifest[T]

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

val json: JSONObject = JSON.parseObject(line)
println(json.get("id").toString)

pom.xml
<dependency>  <groupId>com.alibaba</groupId>  <artifactId>fastjson</artifactId>  <version>1.2.47</version></dependency>
相關文章
相關標籤/搜索