Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails - How to unregister an already registered object marshaller

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

In one context, I need to render only a couple of fields (say id and name). In another context, I want to render a lot more (id, name, credentials, age etc..). I'm wondering if it is possible to unregister a particular marshaller right after use.

Essentially what I'm looking for is 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 have separate Marshallers registered for each. As the number of contexts increase the number of dummy subclasses will also go up. This is very unclean imo.

like image 658
techfoobar Avatar asked Jan 07 '14 08:01

techfoobar


1 Answers

You'd probably want to use what's called a named config instead of 'swapping' marshallers. You can wrap this up into a neater class/utility, but somewhere (like 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 a controller, you can choose which style of marshalled 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
}
like image 85
Joe Rinehart Avatar answered Oct 17 '22 11:10

Joe Rinehart