smeeb
smeeb

Reputation: 29567

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

Upvotes: 3

Views: 17452

Answers (1)

doelleri
doelleri

Reputation: 19702

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."]'

Upvotes: 13

Related Questions