I am marshaling objects in Grails to JSON using the JSON.registerObjectMarshaller() method, which is invoked in the BootStrap class.
My object graph has a number of nested objects e.g. User -> Address -> Phone and I have a marshaller for each object.
I have a scenario where I want to be able to either return a “shallow” or “deep” version of the top level object. In the case of a shallow request, in place of the address I want to return the field. In the case of the a deep version, the other object marshalers can do delegated to as usual.
I want to do a deep versus shallow based on the value of a parameter passed in the request, however I do not know how to access request parameters when in the registerObjectMarshaller() method from the BootStrap class.
Once I have a way to access these parameters I can tailor it as needed.
Any pointers would be greatly appreciated.
I once tried the object marshaller approach for XML and sadly it didn’t work out.
Similar to you, I don’t have one way to represent objects. I have a lot more than two, but I think Object Marshallers are a way to go only if you want to do something trivial. If you need more, just forget about them.
It may be much easier for you, to simply create a service or a class with static methods which will generate the JSON for you based on the values you pass.
You can use JsonGroovyBuilder to achieve that, and then just convert it to string and wrap it in a nice http header or whatever you need.
In my case it looks like this [mind you, this is for XML, so you have to use JsonGroovyBuilder, or other – whichever suits you – and you will probably not need to use the StringWriter as I do]: