Friday, July 17, 2009

Using a list or a map to construct JSON dynamiclly

How do you contruct a dynamic JSON, especially when you only need to return some fields of an object not a whole object? Using a builder or constructing a string directly? Neither is my favorite.
As time playing grails goes on, I find another way to build a JSON, only two steps:
1. To fill a list or a map with your data.
2. Using "as JSON".
Here is a sample:

def toc= TutorialRepository.toc
int i=1
int j=1
def tocJson=[]
toc.each{ ch ->
def chJson= [:]
chJson['title']= ch.title
chJson['sections']= []
ch.sections.each{ se ->
def seJson= [:]
seJson['title']= se.title
seJson['pos']= "${i}:${j}"
chJson['sections'] << seJson
j++
}
tocJson << chJson
i++
j= 1
}

render tocJson as JSON

It's simple, right? And there are several advantages in this way building a JSON:
1. It makes code clean.
2. You can build more expressive JSON.
3. It is more intuitive as the structure of the list(or the map) is the structure of the final JSON.

1 comment:

Amit said...

Thanks for sharing this. It reduces the code size and possible errors.

Regards,
Amit Jain