本文共 1010 字,大约阅读时间需要 3 分钟。
原博客地址:
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)}
转载地址:http://gmnrj.baihongyu.com/