使用Scala Parser解析JSON

来源:互联网 发布:商品降价提醒软件 编辑:程序博客网 时间:2024/05/16 11:07

原博客地址:使用Scala Parser解析JSON

import scala.util.parsing.combinator._class JsonParser extends JavaTokenParsers {def jNum: Parser[Double] = floatingPointNumber ^^ (_.toDouble)def jStr: Parser[String] = stringLiteral ^^ (s => s.substring(1, s.length() - 1))def jBool: Parser[Boolean] = "(true|false)".r ^^ (_.toBoolean)def jNull: Parser[Null] = "null".r ^^ (t => null)def term = jsonArray | jsonObject | jNum | jBool | jNull | jStrdef jsonArray: Parser[List[Any]] = "[" ~> rep(term <~ ",?".r) <~ "]" ^^ (l => l)def jsonObject: Parser[Map[String, Any]] = "{" ~> rep((ident ~ ":" ~ jNum |ident ~ ":" ~ jBool |ident ~ ":" ~ jNull |ident ~ ":" ~ jsonObject |ident ~ ":" ~ jsonArray |ident ~ ":" ~ jStr) <~ ",?".r) <~ "}" ^^ {os =>var map = Map[String, Any]()os.foreach(o =>o match {case k ~ ":" ~ v => map = map ++ Map(k -> v)})map}}
object JsonParser_Ex extends JsonParser with App{val result = parseAll(jsonObject, """{a:[1,2,"a",{name:"cc"}],b:1,c:"cc",d:null,e:true}""")println(result)}



0 0