Scala解析Json格式
阿新 • • 發佈:2018-12-03
程式碼塊
Scala原生包
匯入包
import scala.util.parsing.json._
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
GSON包
匯入包
import com.google.gson.{JsonObject, JsonParser}
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