Reputation: 29567
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