Scala解析Json获取指定key的值

import scala.util.parsing.json._
object Scala_Json {
  def main(args: Array[String]): Unit = {

     def regJson(json:Option[Any])=json match{
       case Some(map:Map[String,Any]) => map
     }

    val str="{\"host\":\"td_test\",\"ts\":1486979192345,\"device\":{\"tid\":\"a123456\",\"os\":\"android\",\"sdk\":\"1.0.3\"},\"time\":1501469230058}"
    val jsonS = JSON.parseFull(str)
    val first = regJson(jsonS)
     // 获取一级key
    println(first.get("host"))  // Some(td_test)
    // 获取二级key
    val dev = first.get("device")
    println(dev)   // Some(Map(tid -> a123456, os -> android, sdk -> 1.0.3))
    val sec = regJson(dev)
    val scc=sec.get("tid").toString
    println(scc) // Some(a123456)
    val sss= scc.replaceAll("\\(|\\)|Some","") //scala 转义
    val sis = scc.split("\\(")(1).split("\\)")(0)
    println("sis:"+sis) //sis:a123456
    println("sss:"+sss)//sss:a123456
    val a = sec.get("tid").toArray
    println(sec.get("tid").toString.replace("Some(","").replace(")",""))//a123456
    val st = str.replaceAll("\\\\|\\{|\\}|:|","")
    println(st)
     }
}

打印结果

Scala解析Json获取指定key的值_第1张图片

你可能感兴趣的:(Scala)