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.


Siddhartha said...

I am using the 0.5 joda plugin as well as i tried the Bootstrap solution given in your post I am still getting an exception when I am using DateTime

at org.mortbay.thread.QueuedThreadPool$
Caused by: java.lang.NullPointerException
at grails.converters.JSON.value(
at grails.converters.JSON.convertAnother(
at grails.converters.JSON.value(
at grails.converters.JSON.convertAnother(
at grails.converters.JSON.value(
at grails.converters.JSON.render(
at grails.converters.JSON.render(
at com.test.PersonController$_closure3.doCall(PersonController.groovy:2
at com.test.PersonController$_closure3.doCall(PersonController.groovy)

Could you please help

J-Wicz said...
This comment has been removed by the author.
J-Wicz said...

Dear Rob this blog post of yours, was one of my source for this longer post about XML marshalling. Thanks for the hints


Erik Pragt said...

Interesting reads! Today, my colleague Marcin also posted an interesting article about marshalling using annotations in JSON. You can find it here:

maan said...

I have read your blog it's very attractive and impressive. I like your blog.
Vidmate Apk Download