Created
November 5, 2012 01:05
-
-
Save srhea/4014652 to your computer and use it in GitHub Desktop.
A thread-safe version of scala.util.parsing.json.JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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