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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With