Grails: Named Marshaller

a small particle of knowledge in the Grails universe… :-)

I like to strip the data marshalled to an api consumer to a bare minimum. For example the default Grails marshaller adds the class name and version of a domain class to the json. Usually no information that will be used on the client side of an application.
We can easily change the default and remove all unnecessary information by registering a new standard marshaller:

    JSON.registerObjectMarshaller(Foo) {
        [description:'this is a standard foo!']

The standard marshaller is still a bit limiting. We have just one representation for all api calls. If we have multiple api calls using the same domain objects we have to add everything required by the request that does work on the biggest data set. The other requests will receive more data than they need. Not what we want.

Grails supports named marshaller which will remove this limitation. We can register multiple marshallers fora single domain class by giving them names. We can register marshallers of different domain objects using the same name. That means we can group them by feature, user rights or whatever we like.

To register a named marshaller we use the following code:

JSON.createNamedConfig ('feature') { DefaultConverterConfiguration<JSON> cfg ->
    cfg.registerObjectMarshaller (Foo) { Foo it, JSON json ->
        [description: 'this is a named foo!']

To use the named marshaller we wrap as JSON in JSON.use():

JSON fooConverter  = JSON.use ('feature') {
    foo as JSON


foo as JSON

will still use the standard marshaller.

So simple. :-)

This is described in the renderers section of the Grails doumentation.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s