Wednesday, April 26, 2017

JSON Rendering Your Classes

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 Jodas 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: DateTimeMarshaller.java. After that all thats required is to register the new renderer in BootStrap.groovy or some other appropriate spot with:

grails.converters.JSON.registerObjectMarshaller new DateTimeMarshaller()

Ill be adding this to the next release of the Joda Time Plugin so that its completely transparent.

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

JSON.registerObjectMarshaller(DateTime) {
return it?.toString("yyyy-MM-ddTHH:mm:ssZ")
}

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

Available link for download