Fork me on GitHub

12 Aug 2009

JSON Rendering Your Classes

It turns out adding custom JSON renderers for your own types to Grails is really easy. Since I habitually use Joda Time instead of the horrible java.util.Date and even more horrible java.util.Calendar I need to be able to render classes such as Joda's DateTime as JSON so that domain objects with fields of those types will convert properly.

Implementing a renderer for a type is as easy as this: After that all that's required is to register the new renderer in BootStrap.groovy or some other appropriate spot with:

grails.converters.JSON.registerObjectMarshaller new DateTimeMarshaller()

I'll be adding this to the next release of the Joda Time Plugin so that it's completely transparent.

Update: Actually it's even easier than I thought. This being Groovy you can just use closures like so:

JSON.registerObjectMarshaller(DateTime) {
return it?.toString("yyyy-MM-dd'T'HH:mm:ss'Z'")

Update: This is now built in to version 0.5 of the Joda Time Plugin.