9.1.6.2 Registering Custom Objects Marshallers - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.0.12
9.1.6.2 Registering Custom Objects Marshallers
Grails' Converters feature the notion of an ObjectMarshaller and each type can have a registeredObjectMarshaller
. You can register custom ObjectMarshaller
instances to completely customize response rendering. For example, you can define the following in BootStrap.init
:XML.registerObjectMarshaller Book, { Book book, XML xml -> xml.attribute 'id', book.id xml.build { title(book.title) } }
JSON.registerObjectMarshaller(DateTime) { return it?.toString("yyyy-MM-dd'T'HH:mm:ss'Z'") }
JSON.registerObjectMarshaller(Book) {
def map= [:]
map['titl'] = it.title
map['auth'] = it.author
return map
}
Registering Custom Marshallers via Spring
Note that if you have many custom marshallers it is recommended you split the registration of these into a separate class:class CustomMarshallerRegistrar { @javax.annotation.PostConstruct void registerMarshallers() { JSON.registerObjectMarshaller(DateTime) { return it?.toString("yyyy-MM-dd'T'HH:mm:ss'Z'") } } }
grails-app/conf/spring/resources.groovy
:beans = { myCustomMarshallerRegistrar(CustomMarshallerRegistrar) }
PostConstruct
annotation will get triggered on startup of your application.