joshft91
joshft91

Reputation: 1885

Groovy map to json list of objects

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"
}

Upvotes: 13

Views: 33994

Answers (1)

daggett
daggett

Reputation: 28564

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']))

Upvotes: 27

Related Questions