I recently did this with the Grails application and found it is surprisingly easy to take the generated controllers and make them output JSON or XML or HTML from the view depending on content consistency.
The places to learn in the Grails tutorial are the content content section and, if you need to deal with JSON or XML input, marshaling.
To get the JSON and XML output in the list()
method by default, he changed it to this (I have a Session
object, in this case ... one of my domain classes):
def list() { params.max = Math.min(params.max ? params.int('max') : 10, 100) def response = [sessionInstanceList: Session.list(params), sessionInstanceTotal: Session.count()] withFormat { html response json {render response as JSON} xml {render response as XML} } }
withFormat
you return the default object, you need to replace the return value with the withFormat
block.
You may also need to update the Config.groovy file, where it deals with the mime type. Here is what I have:
grails.mime.file.extensions = true // enables the parsing of file extensions from URLs into the request format grails.mime.use.accept.header = true grails.mime.types = [ html: ['text/html','application/xhtml+xml'], xml: ['text/xml', 'application/xml'], text: 'text/plain', js: 'text/javascript', rss: 'application/rss+xml', atom: 'application/atom+xml', css: 'text/css', csv: 'text/csv', all: '*/*', json: ['application/json','text/json'], form: 'application/x-www-form-urlencoded', multipartForm: 'multipart/form-data' ]
As input (for example, for the update()
or save()
action), the JSON and XML data will be automatically unmarshaled and will be bound in the same way as the form input, but I found that the markup process is a bit picky (especially with JSON) .
I found that for the correct JSON handling in the update()
method, the class
attribute must be present and corrected on the incoming JSON object. Since the library that I used in my client application did not help solve this problem, I switched to using XML instead.