Scalaにおけるjson形式、文字列、map相互変換

1517 ワード

jsonオブジェクトをjson文字列に変換するには、次の手順に従います.
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に変換されます.
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]