Using Groovy JSON builder

647 views Asked by At

I've seen several really cool examples of Groovy and Grails JSON builder. Here's one: http://www.objectpartners.com/2012/03/22/grails-protip-dynamically-creating-json-in-grails-2-0-with-jsonbuilder/

Right now I'm using a controller to generate test list using using collect and then render the list into a JSON object. Does anyone know how to take the above example and put it into a controller?

Here's what my controller looks like:

class TreeMapController {

def list(){

    def results = myDomain.list()

    def test = [:] //Test List

    test=[] 

    def i = 0 //index key for parent

    //Generate list for fancyTree
    for (record in results){
        test.add([key:i++,folder:true, title: record.name, guid: record.id,
                children:record.subResults.collect{[title:it.name]}

        ])
    }

    //render response types
    withFormat {
        html test
        json {render test as JSON}
        xml {render test as XML}
    }
}

}

To call this using json request I provide the link: localhost/project/list.json if I was to call the example provided (link to using JSON builder) above how would I call or make the request.

1

There are 1 answers

0
Grooveek On BEST ANSWER

You definitely should have a look on Grails Documentation to understand basic concepts

Here, you have a controller that will respond to ${baseUrl}/treeMap/list url, that is to say http://localhost:8080/treeMap/list as per the defaults

You'll have to request the URL with a Content-type: text/json; header, I think, to make it work