Skip to content

Instantly share code, notes, and snippets.

@greggigon
Last active September 27, 2016 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggigon/5587666 to your computer and use it in GitHub Desktop.
Save greggigon/5587666 to your computer and use it in GitHub Desktop.
I always find myself using a lot of HashMaps in Groovy where in Java I would create a Pojo or something. This little gist turns the map into a somehow formatted JSON. The code assumes that maps are keyed by Strings, can contain other Maps, Lists or Objects. If the map value is an object .toString() will be used to get it's value. Proved useful w…
class JsonMap {
def toJSON(elements, depth = 0) {
def json = ""
depth.times { json += "\t" }
json += "{"
elements.each { key, value ->
json += "\"$key\":"
json += jsonValue(value, depth)
json += ", "
}
json = (elements.size() > 0) ? json.substring(0, json.length() - 2) : json
json += "}"
json
}
private def jsonValue(element, depth) {
if (element instanceof Map) {
return "\n" + toJSON(element, depth + 1)
}
if (element instanceof List) {
def list = "["
element.each { elementFromList ->
list += jsonValue(elementFromList, depth)
list += ", "
}
list = (element.size() > 0) ? list.substring(0, list.length() - 2) : list
list += "]"
return list
}
(element instanceof String) ? "\"$element\"": element?.toString()
}
}
class MapToJsonTests extends GroovyTestCase {
private final def mapper = new JsonMap()
void test_convertMapWithListsOfMapsIntoJSON() {
def map = ["a": "a", "b": [["b": "a"], 'd', [12, 12, "e"], ["r": 12]]]
def expected = '''{"a":"a", "b":[
\t{"b":"a"}, "d", ["12", "12", "e"],
\t{"r":"12"}]}'''
def result = mapper.toJSON(map)
assert expected == result
}
}
@focampo
Copy link

focampo commented Jan 23, 2014

Hi there. I might be missing something but, as it is, the Test Case is missing the definition of the "mapper" variable (an instance of JsonMap). Other possible approach would be to define the "toJSON" method as static.

(update)
If you change the last line of the jsonValue method from

"\"$element\""

to

return (element instanceof String) ? "\"$element\"" : element?.toString()

you can support other data types like numbers or booleans.

Regards,

@greggigon
Copy link
Author

Valid points. Thanks. I did make the changes suggested by you.

@Mahesha999
Copy link

Mahesha999 commented Sep 27, 2016

isnt this possible with JsonOutput.prettyPrint(JsonOutput.toJson(mapObject))? or this code does something else/more. Or this method was introduced later?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment