使用Groovy将字符串列表转换为JSON

时间:2015-10-19 20:20:59

标签: json groovy

我有一个像这样的字符串列表:

List<String> errors = []
errors << 'Your password was bad.'
errors << 'Your feet smell.'
errors << 'I am having a bad day.'

我想将(通过Groovy /第三方库)转换为JSON:

{
    [
        "Your password was bad.",
        "Your feet smell.",
        "I am having a bad day."
    ]
}

到目前为止,我最好的尝试是讨厌,我希望有更快/更精简/更有效的方法:

static String errorsToJSON(List<String> errors) {
    StringBuilder sb = new StringBuilder()
    sb.append('{ ')
    List<String> errorJsons = []
    errors.each {
        errorJsons << '\"${it}\"'
    }

    // https://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Joiner.html
    List<String> list = Joiner.on(',').join(errorJsons)
    list.each {
        sb.append(it)
    }
    sb.append(' }')

    sb.toString()
}

1 个答案:

答案 0 :(得分:8)

不需要第三方库,Groovy可以为您完成所有这些。

def json = groovy.json.JsonOutput.toJson(errors)
assert json == '["Your password was bad.","Your feet smell.","I am having a bad day."]'