Skip to content

Instantly share code, notes, and snippets.

@greggigon

greggigon/JsonMap.groovy

Last active Sep 27, 2016
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@focampo 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

This comment has been minimized.

Copy link
Owner Author

@greggigon greggigon commented May 13, 2014

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

@Mahesha999

This comment has been minimized.

Copy link

@Mahesha999 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
You can’t perform that action at this time.