19

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"
}

3 Answers 3

38

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 render method 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 this

def results = db.rows(query).collect { rowResult ->
    b(rowResult.name, c, d) 
}
render(contentType: 'text/json') {[
    'results': results,
    'status': results ? "OK" : "Nothing present"
]}

I think it's more readable, and even shorter. This snippet gets you the desired result: no objects inside the results array, 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 value a by calling b on 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/json content type and passing it a literal map containing the keys results and status, 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:

def responseData = [
    'results': results,
    'status': results ? "OK" : "Nothing present"
]
render responseData as JSON
6
  • 1
    I like your last code snippet better than the first one. It's probably more debugger-friendly also.
    – epidemian
    Commented Mar 10, 2012 at 4:41
  • Yep, that JSON converter is definitely the way to go :)
    – Will Buck
    Commented Mar 12, 2012 at 1:28
  • 1
    Having issues with your last snippet in Grails 2.0. The response is rendered as text enclosed in {}.
    – raffian
    Commented Aug 24, 2012 at 15:52
  • @SAFX I don't know why I never saw this comment. Anyway, it is enclosed in {} because that's how objects are enclosed in JSON: json.org
    – Esteban
    Commented Mar 27, 2013 at 16:42
  • what the need of "status" please ? is it to check manually (I mean like if(status==....){ ....} ) if something is found or it something grails/JS(client side ...) needs? ? thank you Commented Aug 7, 2016 at 15:23
6

Only off by a little bit :) Just need to change

aMap.put("A", a)

to be a collection or list, rather than a map. so something like

def aList = []
aList << a

Will get you what you want!

As a sidenote, there is a JSON converter in grails that will do that string building for you. Look into it here

2

This should be enough to render a JSON from controller:

render results as grails.converters.JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.