Created
November 5, 2013 02:24
-
-
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.
This file contains hidden or 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
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 | |
} | |
} |
This file contains hidden or 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
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