Skip to content

Instantly share code, notes, and snippets.

@Mononofu
Created September 18, 2012 11:34
Show Gist options
  • Save Mononofu/3742702 to your computer and use it in GitHub Desktop.
Save Mononofu/3742702 to your computer and use it in GitHub Desktop.
Beautiful JSON handling in Scala
package EasyJSON
import net.minidev.json.JSONValue
import net.minidev.json.JSONArray
import net.minidev.json.JSONObject
import scala.collection.JavaConversions._
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 extends Exception
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
}
def toDouble: Double = o match {
case d: java.lang.Double => d
case f: java.lang.Float => f.toDouble
case _ => throw new JSONException
}
def apply(key: String): ScalaJSON = o match {
case m: JSONObject => new ScalaJSON(m.get(key))
case _ => throw new JSONException
}
def apply(idx: Int): ScalaJSON = o match {
case a: JSONArray => new ScalaJSON(a.get(idx))
case _ => throw new JSONException
}
def length: Int = o match {
case a: JSONArray => a.size()
case m: JSONObject => m.size()
case _ => throw new JSONException
}
def iterator: Iterator[ScalaJSON] = o match {
case a: JSONArray => new ScalaJSONIterator(a.iterator())
case _ => throw new JSONException
}
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)
}
}
}
package EasyJSON
import JSON._
object Test extends App {
print("Fetching recent data ...")
val json = io.Source.fromURL("http://liquid8002.untergrund.net/infinigag/").mkString
println(" done\n")
val tree = parseJSON(json)
println("next page: %d\n".format(tree.attributes.next.toInt))
println("=== Top %d images from 9gag ===".format(tree.images.length))
tree.images.foreach {
case image =>
println("%s: %s".format(image.title, image.image.thumb))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment