Scala解析Json格式

原创
2019/06/30 23:01
阅读数 4.5W
import scala.util.parsing.json._ //使用scala原生包
def main(args: Array[String]): Unit = {

    def regJson(json:Option[Any]) = json match {
      case Some(map: Map[String, Any]) => map
//      case None => "erro"
//      case other => "Unknow data structure : " + other
    }
    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"))
    // 获取二级key
    val dev = first.get("device")
    println(dev)
    val sec = regJson(dev)
    println(sec.get("tid").toString.replace("Some(","").replace(")",""))
  }

// 运行结果
Some(td_test)
Some(Map(tid -> a123456, os -> android, sdk -> 1.0.3))
a123456

import com.google.gson.{JsonObject, JsonParser}  //使用Gson包
def main(args: Array[String]): Unit = {

    gson("{\"host\":\"td_test\",\"ts\":1486979192345,\"device\":{\"tid\":\"a123456\",\"os\":\"android\",\"sdk\":\"1.0.3\"},\"time\":1501469230058}")

  }

  def gson(str: String) ={
    val json = new JsonParser()
    val obj = json.parse(str).asInstanceOf[JsonObject]
    println(obj.get("device"))
    println(obj.get("ts"))
  }

// 运行结果:

{"tid":"a123456","os":"android","sdk":"1.0.3"}
1486979192345

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部