Skip to content

Instantly share code, notes, and snippets.

@gordonkristan
Created November 5, 2013 02:24
Show Gist options
  • Save gordonkristan/7312813 to your computer and use it in GitHub Desktop.
Save gordonkristan/7312813 to your computer and use it in GitHub Desktop.
Small batch of JSON helper functions for Scala and the Google GSON library.
object JsonHelper {
def JSON(props: (String, JsonElement)*): JsonObject = {
props.foldLeft(new JsonObject)((json, pair) => {
json.add(pair._1, pair._2)
json
})
}
implicit def string2json(s: String) = new JsonPrimitive(s)
implicit def number2json(n: Number) = new JsonPrimitive(n)
implicit def boolean2json(b: Boolean) = new JsonPrimitive(b)
implicit def list2array(lis: List[Any]): JsonArray =
lis.foldLeft(new JsonArray)((array, item) => {
array.add(convertToJson(item))
array
})
def convertToJson(obj: Any): JsonElement = obj match {
case e: JsonElement => e
case lis: List => list2array(lis)
case s: String => new JsonPrimitive(s)
case n: Number => new JsonPrimitive(n)
case b: Boolean => new JsonPrimitive(b)
case null => JsonNull.INSTANCE
case _ => throw new RuntimeException
}
}
object Test {
def main(args: Array[String]) {
val json = JSON(
"lis" -> List("", true, 2.0, 3L, JSON(), null),
"obj" -> JSON(
"nested_key" -> JSON()
)
)
System.out.println(json)
// {"lis":["",true,2.0,3,{},null],"obj":{"nested_key":{}}}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment