Groovy映射到JSON对象列表

时间:2018-06-27 17:42:50

标签: groovy

我正在尝试绘制一个非常简单的对象图,并像这样生成对象列表。我已经完成了这项工作,但是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'])

将产生:

{
  "test": "test",
  "test2": "test2"
}

1 个答案:

答案 0 :(得分:1)

序列化映射到json对象(字符串)

您可以使用

http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonBuilder.html

import groovy.json.JsonBuilder
new JsonBuilder([test: 'test', test2: 'test2']).toPrettyString()

http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonOutput.html

import groovy.json.JsonOutput
JsonOutput.prettyPrint(JsonOutput.toJson([test: 'test', test2: 'test2']))