Grails - How to unregister an already registered object marshaller

I have a Person domain class in my grails application that I need to output in different forms (JSON) depending on the context.

In one context, I only need to display a couple of fields (e.g. id and name). In another context, I want to do a lot more (id, name, credentials, age, etc.). I am wondering if it is possible to unregister a specific marshaller immediately after use.

Essentially, I'm looking for something like:

 ------------------------------------------------------------- // context #1 JSON.registerObjectMarshaller(Person) { ... output just id and name } render myPerson as JSON JSON.unregisterObjectMarshaller(Person) // how do i do this? ------------------------------------------------------------- // context #2 JSON.registerObjectMarshaller(Person) { ... output all fields } render myPerson as JSON JSON.unregisterObjectMarshaller(Person) // how do i do this? ------------------------------------------------------------- 

Note. I can create 2 empty subclasses for Person, and then separate marshalers are marked for each of them. As the number of contexts increases, the number of dummy subclasses also increases. This is a very unclean imo.

+6
source share
1 answer

You probably want to use the so-called named config instead of swapping marshalers. You can wrap this in a neater class / utility, but somewhere (e.g. Bootstrap.groovy) do:

 JSON.createNamedConfig('thin') { it.registerObjectMarshaller( Person ) { Person person -> return [ id: person.id, name: person.name, ] } } JSON.createNamedConfig('full') { it.registerObjectMarshaller( Person ) { Person person -> return [ id: person.id, name: person.name, age: person.age ] } } 

Then, in the controller, you can choose which style of marshalling person to show:

 // Show lots of stuff JSON.use('full') { render people as JSON } 

or

 // Show less stuff JSON.use('thin') { render people as JSON } 
+17
source

All Articles