|
| 1 | +package com.bne.util |
| 2 | +package json |
| 3 | + |
| 4 | +import net.minidev.json.JSONValue |
| 5 | +import net.minidev.json.JSONArray |
| 6 | +import net.minidev.json.JSONObject |
| 7 | + |
| 8 | +import scala.collection.JavaConversions._ |
| 9 | +import scala.language.dynamics |
| 10 | + |
| 11 | +object JSON { |
| 12 | + implicit def parseJSON(s: String) = new ScalaJSON(JSONValue.parse(s)) |
| 13 | + def makeJSON(a: Any): String = a match { |
| 14 | + case m: Map[String, Any] => m.map { |
| 15 | + case (name, content) => "\"" + name + "\":" + makeJSON(content) |
| 16 | + }.mkString("{", ",", "}") |
| 17 | + case l: List[Any] => l.map(makeJSON).mkString("[", ",", "]") |
| 18 | + case l: java.util.List[Any] => l.map(makeJSON).mkString("[", ",", "]") |
| 19 | + case s: String => "\"" + s + "\"" |
| 20 | + case i: Int => i.toString |
| 21 | + } |
| 22 | + |
| 23 | + implicit def ScalaJSONToString(s: ScalaJSON) = s.toString |
| 24 | + implicit def ScalaJSONToInt(s: ScalaJSON) = s.toInt |
| 25 | + implicit def ScalaJSONToDouble(s: ScalaJSON) = s.toDouble |
| 26 | +} |
| 27 | + |
| 28 | +case class JSONException extends Exception |
| 29 | + |
| 30 | +class ScalaJSONIterator(i: java.util.Iterator[java.lang.Object]) extends Iterator[ScalaJSON] { |
| 31 | + def hasNext = i.hasNext() |
| 32 | + def next() = new ScalaJSON(i.next()) |
| 33 | +} |
| 34 | + |
| 35 | +class ScalaJSON(o: java.lang.Object) extends Seq[ScalaJSON] with Dynamic { |
| 36 | + override def toString: String = o.toString |
| 37 | + def toInt: Int = o match { |
| 38 | + case i: Integer => i |
| 39 | + case _ => throw new JSONException |
| 40 | + } |
| 41 | + def toDouble: Double = o match { |
| 42 | + case d: java.lang.Double => d |
| 43 | + case f: java.lang.Float => f.toDouble |
| 44 | + case _ => throw new JSONException |
| 45 | + } |
| 46 | + def apply(key: String): ScalaJSON = o match { |
| 47 | + case m: JSONObject => new ScalaJSON(m.get(key)) |
| 48 | + case _ => throw new JSONException |
| 49 | + } |
| 50 | + |
| 51 | + def apply(idx: Int): ScalaJSON = o match { |
| 52 | + case a: JSONArray => new ScalaJSON(a.get(idx)) |
| 53 | + case _ => throw new JSONException |
| 54 | + } |
| 55 | + def length: Int = o match { |
| 56 | + case a: JSONArray => a.size() |
| 57 | + case m: JSONObject => m.size() |
| 58 | + case _ => throw new JSONException |
| 59 | + } |
| 60 | + def iterator: Iterator[ScalaJSON] = o match { |
| 61 | + case a: JSONArray => new ScalaJSONIterator(a.iterator()) |
| 62 | + case _ => throw new JSONException |
| 63 | + } |
| 64 | + def isNull = o == null |
| 65 | + |
| 66 | + def selectDynamic(name: String): ScalaJSON = apply(name) |
| 67 | + def applyDynamic(name: String)(arg: Any) = { |
| 68 | + arg match { |
| 69 | + case s: String => apply(name)(s) |
| 70 | + case n: Int => apply(name)(n) |
| 71 | + case u: Unit => apply(name) |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments