Last active
September 27, 2016 12:34
-
-
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…
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
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() | |
} | |
} | |
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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
isnt this possible with
JsonOutput.prettyPrint(JsonOutput.toJson(mapObject))
? or this code does something else/more. Or this method was introduced later?