Skip to content

Instantly share code, notes, and snippets.

@srhea
Created November 5, 2012 01:05
Show Gist options
  • Save srhea/4014652 to your computer and use it in GitHub Desktop.
Save srhea/4014652 to your computer and use it in GitHub Desktop.
A thread-safe version of scala.util.parsing.json.JSON
// A thread-safe version of scala.util.parsing.json.JSON, as suggested
// by Matthew Neeley in response to a question on the Bay Area Scala
// Enthusiasts mailing list. Covered by the standard Scala license.
import scala.util.parsing.json.{ Parser => JSONParser, JSONObject, JSONArray }
class JSON extends JSONParser {
private def resolveType(input: Any): Any = input match {
case JSONObject(map) => map.transform { case (k,v) => resolveType(v) }
case JSONArray(seq) => seq.map(resolveType)
case other => other
}
def parse(input: String): Option[Any] = {
phrase(root)(new lexical.Scanner(input)) match {
case Success(result, _) => Some(resolveType(result))
case _ => None
}
}
}
object JSON {
// Could instead cache one parser per thread in a thread local variable,
// but that only gives about a 10% performance improvement.
def parse(input: String): Any = (new JSON).parse(input)
}
object JSONExample {
def main(args: Array[String]) {
println(JSON.parse("""{"foo": 1, "bar": "hello"}"""))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment