Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to parse Json format in Scala

Shulou Source: shulou.com Published: 2022-06-02 05:59:27 10月23日 Update

How to parse Json format in Scala? I believe many inexperienced people don't know what to do about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Import scala.util.parsing.json._ / / use scala native package 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) / / get level 1 key println (first.get (" host ")) / / get level 2 key val dev = first.get (" device ") println (dev) val sec = regJson (dev) println (sec.get (" tid ") .toString.replace (" Some (","). Replace (")" "")} / / run result Some (td_test) Some (Map (tid-> a123456, os-> android, sdk-> 1.0.3)) a123456import com.google.gson. {JsonObject, JsonParser} / / use Gson package 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 "))} / / result: {" tid ":" a123456 "," os ":" android " "sdk": "1.0.3"} 1486979192345 finish reading the above content Have you mastered the method of parsing Json format in Scala? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Format content method more results problems operation helplessness for this reason skills articles experience industry information information channels channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Huawei Microsoft MySQL MariaDB