1

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?

2 Answers 2

3

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.

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

render(contentType: 'application/json') {
   [lists: list]
}
3
  • Thanks! How do i add the JSON tag 'LIST' before each separate name/id?
    – maloney
    Mar 12, 2014 at 15:20
  • 1
    You can't have a map with multiple identical keys
    – tim_yates
    Mar 12, 2014 at 15:26
  • Yea, what tim_yates said. Once you realize JSON is just a MAP, it will make things easier on you.
    – Gregg
    Mar 12, 2014 at 15:35

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.