JSON Output In Grails Controller

I wanted to be able to output an object with all the domain properties. This is obviously very easy in Grails:

1
MyObject as JSON

What if you wanted to be able to add to the MyObject? There are a bunch of ways that Grails provides in order to allow you to let you do this. Unfortunately, I didn’t know all of them at first so I had to do a bit of research.

Since I just wanted to add a simple property to render I added a transient value to my object:

1
static transients = ["link"]

Then I was able to set this value in the controller by iterating over my objects:

1
myObjectList.each() { it.href = createLink(action:'show', id:it.id).encodeAsHTML() };

Then I could just do the following:

1
render json as JSON

Bang! I have my extra attribute! Depending on what you want to do there might be a better way for your particular situation. As far as the code is concerned, this was a nice short change.

If more is needed I might need to start using the ObjectMarshaller. You can read about that and other ways to work with JSON by visiting the link below. They were probably the best resources I found out there at the moment.

Excellent blog:
Rending JSON Part 2: http://manbuildswebsite.com/2010/02/08/rendering-json-in-grails-part-2-plain-old-groovy-objects-and-domain-objects/

Rending JSON Part 3: http://manbuildswebsite.com/2010/02/15/rendering-json-in-grails-part-3-customise-your-json-with-object-marshallers/

Leave a Reply

Your email address will not be published. Required fields are marked *