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.

Sign up to request clarification or add additional context in comments.

Comments

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

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

3 Comments

Thanks! How do i add the JSON tag 'LIST' before each separate name/id?
You can't have a map with multiple identical keys
Yea, what tim_yates said. Once you realize JSON is just a MAP, it will make things easier on you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.