Tuesday, March 18, 2008

Using JSON Builder with collections

I was having a particular time, doing what I thought would be an easy task. I wanted to use the JSON Builder that would create JSON syntax that I use with the Ext JS framework. I needed JSON to look like this:

{
success:true,
count:1,
data: [
{id:1,task:'Home Page is waiting to be promoted'}
]
}


However no matter what I tried I couldn't get the "data" array to be generated properly. The data elements within the array were being created outside the array. After enough persistence I was finally able to get it to work with this:

def tasks = .... // an array of tasks

render(builder:'json') {
success(true)
count(tasks.size())
data {
tasks.each {
data(
id: it.id,
task: it.task
)
}
}
}



Notice I had to duplicate "data" twice, once outside of the each loop and once inside. I really don't understand why, I'm just glad I figured it out and I can move on! Hopefully this will help if you are stuck with creating arrays with the JSON Builder.

4 comments:

Chrigel said...

thx for the info, exactly what I was looking for :)

Roshan Shrestha said...

I don't know if this will help:

http://www.anyware.co.uk/2005/2008/06/19/a-grails-json-builder-that-doesnt-suck/

Daniel Wood said...

Definitely helped me out!

Paul Holt said...

My God it works!

Thanks a lot, this helped me out considerably.