原博客地址:使用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 | jStr
def 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)
}