Grails 2 - produce JSON output automatically (like Spring 3.x does)

Viewed 1980

In Spring MVC 3.x I can configure a ContentNegotiatingViewResolver bean to automatically render any given endpoint in either JSON or XML simply by changing the file extension to .json or .xml. I assumed there was an equivalent functionality in Grails but I can't find it.

Everything I've read says I have to catch the incoming mime-type (using withFormat) and then specify the JSON output using render as JSON (or equivalent) in every one of my controller methods (e.g. rendering JSON with Grails?). Before I dive in and start adding JSON-specific code to my controllers I thought I'd ask here...

So my question is: Can I configure Grails 2 to automatically produce JSON output by simply adding a `.json' file extension (or changing the accept header) for any given URL?

3 Answers

By accident, I discovered that the latest grails does output JSON and XML automatically by simply setting the Accept header on the query!

I'm using 2.3.2 at the moment but probably the same works for earlier versions and I simply created a new app, created a new simple domain class with some properties, ran generate-all and then run-app. After running it, the curl -i -H "Accept: application/json" returns JSON and curl -i -H "Accept: application/xml" returns XML without any additional work.

I was so surprised with this, that to ensure I haven't installed something strange on my local machine, I tried it on a brand new server with a new grails installation ... and it works!!!

Related