简体   繁体   中英

Convert list of strings into JSON with Groovy

I have a list of Strings like so:

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

That I would like converted (via Groovy/3rd party libs) into JSON:

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

My best attempt thus far is nasty and I expect there is a much quicker/leaner/more efficient way of doing this:

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()
}

No need for a third-party library, Groovy can do this all for you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM