maloney
maloney

Reputation: 1663

Render JSON in Groovy

I have the following code to implement JSON in Groovy:

def index = {
    def list = WordList.list()
    render(contentType:"text/json"){
        LISTS {
            for(item in list){
                LIST (NAME: item.name, ID: item.id);
            }
        }
    }
}

Which almost works but it doesnt show multiple results i.e. the NAME and ID fields get overwritten on each cycle resulting in only the last record getting returned. What is the correct syntax to get this working?

Upvotes: 1

Views: 535

Answers (2)

SurrealAnalysis
SurrealAnalysis

Reputation: 303

My solution in this case is to construct the JSON map explicitly, then render it as JSON.

An example:

def list = WordList.list()
def json = []
list.each{ item ->
    json << [name: item.name, id: item.id]
}
render json as JSON

You will need to import grails.converters.JSON to use this method.

Upvotes: 3

Gregg
Gregg

Reputation: 35904

def list = WordList.list()
list = list.collect { [name: it.name, id: it.id] }

render(contentType: 'application/json') {
   [lists: list]
}

Upvotes: 2

Related Questions