Skip to content

Instantly share code, notes, and snippets.

@Rydgel
Created February 22, 2014 13:04
Show Gist options
  • Save Rydgel/9154511 to your computer and use it in GitHub Desktop.
Save Rydgel/9154511 to your computer and use it in GitHub Desktop.
package riot.Parsing
/**
* Created by Jérôme Mahuet on 22/02/2014.
* http://www.furida.mu/blog/2012/09/18/beautiful-json-parsing-in-scala/
*/
import net.minidev.json.JSONValue
import net.minidev.json.JSONArray
import net.minidev.json.JSONObject
import scala.collection.JavaConversions._
import scala.language.dynamics
object JSON {
def parseJSON(s: String) = new ScalaJSON(JSONValue.parse(s))
def makeJSON(a: Any): String = a match {
case m: Map[String, Any] => m.map {
case (name, content) => "\"" + name + "\":" + makeJSON(content)
}.mkString("{", ",", "}")
case l: List[Any] => l.map(makeJSON).mkString("[", ",", "]")
case l: java.util.List[Any] => l.map(makeJSON).mkString("[", ",", "]")
case s: String => "\"" + s + "\""
case i: Int => i.toString
}
implicit def ScalaJSONToString(s: ScalaJSON) = s.toString
implicit def ScalaJSONToInt(s: ScalaJSON) = s.toInt
implicit def ScalaJSONToDouble(s: ScalaJSON) = s.toDouble
}
case class JSONException(message: String) extends Exception(message)
class ScalaJSONIterator(i: java.util.Iterator[java.lang.Object]) extends Iterator[ScalaJSON] {
def hasNext = i.hasNext
def next() = new ScalaJSON(i.next())
}
class ScalaJSON(o: java.lang.Object) extends Seq[ScalaJSON] with Dynamic {
override def toString: String = o.toString
def toInt: Int = o match {
case i: Integer => i
case _ => throw new JSONException("Unable to convert ScalaJSON to Int")
}
def toDouble: Double = o match {
case d: java.lang.Double => d
case f: java.lang.Float => f.toDouble
case _ => throw new JSONException("Unable to convert ScalaJSON to Double")
}
def apply(key: String): ScalaJSON = o match {
case m: JSONObject => new ScalaJSON(m.get(key))
case _ => throw new JSONException("Unable to convert ScalaJSON to String")
}
def apply(idx: Int): ScalaJSON = o match {
case a: JSONArray => new ScalaJSON(a.get(idx))
case _ => throw new JSONException("Unable to call that method on something different from JSONArray")
}
def length: Int = o match {
case a: JSONArray => a.size()
case m: JSONObject => m.size()
case _ => throw new JSONException("Can't call length on object")
}
def iterator: Iterator[ScalaJSON] = o match {
case a: JSONArray => new ScalaJSONIterator(a.iterator())
case _ => throw new JSONException("Unable to create Iterator")
}
def selectDynamic(name: String): ScalaJSON = apply(name)
def applyDynamic(name: String)(arg: Any) = {
arg match {
case s: String => apply(name)(s)
case n: Int => apply(name)(n)
case u: Unit => apply(name)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment