Created
April 28, 2010 10:32
-
-
Save kmizu/381978 to your computer and use it in GitHub Desktop.
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
import java.io._ | |
object JSONLiteral { | |
sealed trait JSONValue | |
case class JSONObject(members: Map[String, JSONValue]) extends JSONValue | |
case class JSONString(value: String) extends JSONValue | |
case class JSONNumber(value: Double) extends JSONValue | |
case class JSONArray(members: List[JSONValue]) extends JSONValue | |
implicit def int2JSONNumber(value: Int) = JSONNumber(value) | |
implicit def double2JSONNumber(value: Double) = JSONNumber(value) | |
implicit def string2JSONString(value: String) = JSONString(value) | |
def O(members: (String, JSONValue)*): JSONObject = JSONObject(Map(members:_*)) | |
def A(members: JSONValue*): JSONArray = JSONArray(members.toList) | |
def using[A <: { def close() }, B](resource: A)(f: A => B): B = { | |
try { | |
f(resource) | |
} finally { | |
resource.close() | |
} | |
} | |
def dump(jsonObject: JSONObject, to: File, encoding: String) { | |
using(new BufferedWriter( | |
new OutputStreamWriter(new FileOutputStream(to), encoding))){out => | |
out.write(toString(jsonObject)) | |
} | |
} | |
private val escapeMap = Map( | |
'\r' -> 'r', '\n' -> 'n', '\t' -> 't', '\f' -> 'f', | |
'\\' -> '\\', '\'' -> '\'', '\"' -> '\"', '\b' -> 'b') | |
def toString(jsonObject: JSONValue): String = { | |
def escape(content: String): String = { | |
content.foldLeft(new StringBuffer){(buf, ch) => | |
ch match { | |
case ch if escapeMap.contains(ch) => | |
buf.append("\\"); buf.append(escapeMap(ch)) | |
case ch => buf.append(ch) | |
} | |
}.toString | |
} | |
jsonObject match { | |
case JSONObject(members) => | |
members.map{ case (k, v) => "\"" + escape(k) + "\":" + toString(v) } | |
.mkString("{", ",", "}") | |
case JSONString(value) => "\"" + escape(value) + "\"" | |
case JSONArray(members) => members.map(toString(_)).mkString("[", ",", "]") | |
case JSONNumber(value) => value.toString | |
} | |
} | |
} | |
import JSONLiteral._ | |
val obj = | |
O("Name" -> "kmizu", | |
"Country" -> "Japan", | |
"Language" -> A("Scala", "Java")) | |
println(obj) | |
println(JSONLiteral.toString(obj)) | |
val escapeSequence = O("EscapeSequence" -> "\r\n\t\f\\\'\"\b") | |
println(JSONLiteral.toString(escapeSequence)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment