Grails - Creating JSON Views and Templates



Description

JSON views are stored with .gson suffix in grails-app/views directory. These files are Groovy script files which can be edited in any Groovy editor.

The format for JSON view is shown below:

json.student {
   name "jhonson"
}

json is an inbuilt variable, which is a sample shown in StreamingJsonBuilder. The above code will be displayed as shown below−

{"student":{"name":"jhonson"}}

Templates can be defined with underscore _. The following sample code file is named as _student.gson−

model {
   Student student
}
json {
   name student.name
   rollno student.rollno
}

Templates can be presented with views as shown below:

model {
   Division division
}
json {
   name division.teacher.name
   rollno division.student.rollno
   addChild g.render(template:"student", model:[student: division.children.max { Student s -> s.rollno } ])
   children g.render(template:"student", collection: division.children, var:'student')
}

You can use tmpl variable for presenting the above code in more compact way:

model {
   Division division
}
json {
   name division.teacher.name
   rollno division.student.rollno
   addChild tmpl.student( division.children.max { Person s -> s.rollno } ] )
   children tmpl.student( division.children )
}
grails_web_services.htm
Advertisements