I use Groovy a lot. It’s simple and easy to use, runs on JVM and saves me from Java verbosity. I also like the fact that it’s dynamic.
I use it with a simple Servlet to return data to JavaScript AJAX requests. I like to keep the server side very simple, so I don’t create a lot of POJOs and I’m using HashMaps instead. Groovy has few convenient methods that makes it easy to work with Maps.
I do convert the maps into JSON when returning results to a browser. I don’t use anything fancy, just a couple lines of Groovy code to do that.
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
| 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 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
| 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 | |
| } | |
| } |
With this code there is quite a bit of assumptions though:
- it will only work for Map
- it assumes Strings are used as Map Keys
- it will convert Maps, Lists and Objects
- when it meets Object it will call .toString() on it to get it’s value
- it will try to format it with tabs and new lines a bit, so it’s more pleasant for the eye and human readable
Hope it would be useful for you. Greg