拿Scala的Parser写了个解析JSON二维数组的工具

感叹Scala的语法解析器之强大,几行代码就可以搞定我的解析需求,可惜相比专门的JSON解析库(ObjectMapper,fastjson)性能还差很多,不确定是否和apply的处理有关,抽空在研究下。

package cn.zhaishidan.test

import scala.util.parsing.combinator.syntactical._  
import scala.util.parsing.input.CharArrayReader  
import scala.util.parsing.combinator.ImplicitConversions

/**
 * Created by stan on 16/2/17.
 */
object JsonArrayParser extends StdTokenParsers with ImplicitConversions {  
  type Tokens = scala.util.parsing.json.Lexer
  val lexical = new Tokens

  lexical.reserved ++= List("true", "false", "null")
  lexical.delimiters ++= List("[", "]", ",")

  def jsonStr = accept("string", { case lexical.StringLit(n) => n })
  def jsonNum = accept("number", { case lexical.NumericLit(n) => n })
  def jsonVal = jsonStr | jsonNum | "true" ^^^ "true" | "false" ^^^ "false" | "null" ^^^ null
  def jsonArr: Parser[List[String]] = "[" ~> repsep(jsonVal, ",") <~ "]" ^^ (list => list)
  def data: Parser[List[List[String]]] = "[" ~> repsep(jsonArr, ",") <~ "]" ^^ (list => list)

  def apply(s: String): List[List[String]] = {
    phrase(data)(new lexical.Scanner(s)) match {
      case Success(result, _) => result
      case _ => throw new Exception("Illegal JSON format")
    }
  }

}

使用:

val json = """[["1", false], ["true", 4.878], [null, "3"], ["4", null]]"""  
val data = JsonArrayParser(json)  
println(data)