I use the following code to render data in JSON format.
render(contentType:"text/json") {
results = array {
db.eachRow(query) { row ->
def rs = row.toRowResult()
def a = b(rs.name,c,d)
aMap.put("A",a)
pair(aMap)
}
}
if (results) {
status = "OK"
}
else {
status ="Nothing present"
}
}
The above code generates JSON in the following format
{
"results": [
{"A":"value1"},
{"A":"value2"},
...................
{"A":"valuen"}
],
"status":"OK"
}
As u see above, the data is rendered as an array of objects. Is there a way I can render the results data as an array of elements. Like
{
"results": [
"value1",
"value2",
...................
"valuen"
],
"status":"OK"
}
The way the JSON object is being built is quite obscure. What I like doing to render JSON responses in grails is creating a map or list in groovy and then use the
rendermethod just to convert it to JSON.Doing the transformation of the
rowResult‘s inside the render method makes it quite confusing, I’d rather go for something like thisI think it’s more readable, and even shorter. This snippet gets you the desired result: no objects inside the
resultsarray, just strings.Note the use of
rows, which returns a list of RowResult’s, eliminating the need to get it from the ResultSet’s. The list is used to collect the transformed valueaby callingbon each row’s name. Collecting the elements doesn’t imply creating a map (like in the{ "A":"value1"}JSON you were getting), just the same @will-buck achieved with the<<operator on a new, empty list.All we do with the render method is declaring the
text/jsoncontent type and passing it a literal map containing the keysresultsandstatus, which you want to write to the response. The conditional operator is used to concisely determine the status. It could also be used like this, by means of the JSON converter @will-buck also mentioned: