Raja Nagendra Kumar
Raja Nagendra Kumar

Reputation: 790

Grails converters JSON Marshalling on a Instance

In the context of Grails JSON Converters context, looking to transform JSON data which comes as a result of MongoDB Query (the result does not have associated domain object).

One of the fields needs to be transformed (i.e. field having currency symbol needs to be converted to the number by stripping currency symbol).

In such scenario, is it possible to apply marshaller only to this instance data.

Using:

JSON.registerObjectMarshaller(JSONObject)

is applying globally to all the JSONObject in all other places in the code.

I don't wish to create domain objects for this purpose and wish to live with grails converter objects such as JSONObject etc.

Upvotes: 1

Views: 378

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

Yes, you can easily achieve it by using named marshallers. i.e. register your marshaller with same namespace in Bootstrap.groovy:

JSON.createNamedConfig("foo") {
    it.registerObjectMarshaller(new CustomDataMarshaller)
}

Marshaller code:

class CustomDataMarshaller implements ObjectMarshaller<JSON> {

    @Override
    boolean supports(Object object) {
        return object instanceof Currency   // Or directly BasicDbObject if you want to marshall the whole MongoDb result
    }

    @Override
    void marshalObject(Object object, JSON converter) throws ConverterException {
        // Convert here
    }
}

Now use this marshaller only where you want to use it i.e. for any specific instance or result returned from the MongoDB call:

class MyController {

    def test() {
        def data // Any data as you want to marshal

        JSON.use("foo") {
            respond(data)
            // OR
            // render(data as JSON)
        }
    }
}

Upvotes: 1

Related Questions