I'm trying to take a very simple map of objects and produce a list of objects like so. I have this working, but surely there must be a better way with Groovy?
private def createConfigJson(Map configMap) {
def jsonBuilder = new StringBuilder().append("{\n")
configMap.each { key, value ->
jsonBuilder.append(" \"$key\": \"$value\",\n")
}
// Delete last ',' instead of the newline
jsonBuilder.deleteCharAt(jsonBuilder.length() - 2)
jsonBuilder.append("}")
}
createConfigJson([test: 'test', test2: 'test2'])
will produce:
{
"test": "test",
"test2": "test2"
}
to serialize map to json object (string)
you can use
http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonBuilder.html
import groovy.json.JsonBuilder
new JsonBuilder([test: 'test', test2: 'test2']).toPrettyString()
or
http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonOutput.html
import groovy.json.JsonOutput
JsonOutput.prettyPrint(JsonOutput.toJson([test: 'test', test2: 'test2']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With