使用Scala Parser解析JSON
2016-10-07 10:53
211 查看
原博客地址:使用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
}
}
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) }
相关文章推荐
- 灵活组装Json的数据使用Gson的JsonParser和JsonReader解析Json详解例子
- scala中使用fastjson来解析字符串
- 灵活组装Json的数据使用Gson的JsonParser和JsonReader解析Json详解例子
- 灵活组装Json的数据使用Gson的JsonParser和JsonReader解析Json详解例子
- html解析类库htmlparser.net使用方法
- 用glib标准化程序的命令行解析 (option parser ) 使用GOptionEntry
- 在www.json.org上公布了很多Java下的json解析工具,其中org.json和json-lib比较简单,两者使用上差不多
- 使用eval()解析JSON格式字符串应注意的问题
- 转:使用eval()解析JSON格式字符串应注意的问题
- Ajax使用方法,经典Ajax封装,可接收解析后台传回的json对象和json数组
- php使用js保存的json cookie 字符串,然后解析成数组,需要注意的事项
- 使用JSON做Ajax解析服务端返回的JSON对象方法
- bak 6.android xml解析 XmlPullParser的使用.
- 使用JQuery遍历解析由.ashx返回的json的值
- Using GLib's GKeyFile Parser (使用Glib解析配置文件)
- php的JSON 总结 json_decode() 解析错误 及 PEAR JSON.PHP使用
- asp.net使用DataContractJsonSerializer将对象解析为JSON
- 使用安全json parser防止json注入
- 用glib标准化程序的命令行解析 (option parser ) 使用GOptionEntry (转)
- 在 Android 应用程序中使用 Internet 数据 解析 XML、JSON 和 protocol buffers 数据