Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy map to json list of objects

Tags:

groovy

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"
}
like image 418
joshft91 Avatar asked Jun 27 '18 17:06

joshft91


1 Answers

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']))
like image 162
daggett Avatar answered Nov 15 '22 02:11

daggett