Scala解析Json格式
Scala解析Json格式
代码块
-
Scala原生包
导入包
import scala.util.parsing.json._
1 def main(args: Array[String]): Unit = { 2 3 def regJson(json:Option[Any]) = json match { 4 case Some(map: Map[String, Any]) => map 5 // case None => "erro" 6 // case other => "Unknow data structure : " + other 7 } 8 val str = "{\"host\":\"td_test\",\"ts\":1486979192345,\"device\":{\"tid\":\"a123456\",\"os\":\"android\",\"sdk\":\"1.0.3\"},\"time\":1501469230058}" 9 val jsonS = JSON.parseFull(str) 10 val first = regJson(jsonS) 11 // 获取一级key 12 println(first.get("host")) 13 // 获取二级key 14 val dev = first.get("device") 15 println(dev) 16 val sec = regJson(dev) 17 println(sec.get("tid").toString.replace("Some(","").replace(")","")) 18 }
运行结果
Some(td_test)
Some(Map(tid -> a123456, os -> android, sdk -> 1.0.3))
a123456
-
GSON包
导入包
import com.google.gson.{JsonObject, JsonParser}
1 def main(args: Array[String]): Unit = { 2 3 gson("{\"host\":\"td_test\",\"ts\":1486979192345,\"device\":{\"tid\":\"a123456\",\"os\":\"android\",\"sdk\":\"1.0.3\"},\"time\":1501469230058}") 4 5 } 6 7 def gson(str: String) ={ 8 val json = new JsonParser() 9 val obj = json.parse(str).asInstanceOf[JsonObject] 10 println(obj.get("device")) 11 println(obj.get("ts")) 12 }
运行结果:
{"tid":"a123456","os":"android","sdk":"1.0.3"}
1486979192345