3

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

1 Answer 1

13

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."]'
Sign up to request clarification or add additional context in comments.

1 Comment

Another way it is to import static groovy.json.JsonOutput.toJson and use: toJson(errors) (it seems cleaner to me).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.