3

I'm using Grails 2.4.2. As can be seen here:

https://grails.org/Converters+Reference

You can create a static method in your domain with your custom marshaller to render the JSON in the controller. Like that:

Domain:

// a class to output in JSON
    package com.sample
    class User {
       String login
       String passwd

       // JSON definition of the User object
       static {
          grails.converters.JSON.registerObjectMarshaller(User) {
             return [
                     login: it.login
             ]
            }

    }

Then in your controller:

def user = new User(login:'bob', passwd:'1234')
render user as JSON

This is not working for me in my project. I render it and outputs as the default rendering (with class:"com.sample.User"...). But if I change something in the domain and the environment "reloads" it (recompiling), then the render is OK.

Of course, I want the custom marshaller code to be in the domain, and if it's possible with no more other code outside (BootStrap.groovy, resources.groovy...) etc, I know how to do custom marshaller the other way (like here: http://compiledammit.com/2012/08/16/custom-json-marshalling-in-grails-done-right/)

So... what i missed? Is it possible?

2
  • I found that this worked when I did it with command objects (i.e. not domain classes) but it didn't work with domain objects when doing as you're doing (Grails 2.4.3). My domain objects were in a plugin and so I added the JSON.registerObjectMarshaller() method to the plugin's doWithApplicationContext closure within the MyPluginGrailsPlugin.groovy file. Would love to know whether you managed to fix this.
    – John
    Commented May 9, 2015 at 14:27
  • No, I didn't. I worked during a short period in this Grails project and I was wondering why this simple example was failing, but I'm not interested anymore. I'd suggest to file a bug report in the Grails project.
    – jBilbo
    Commented May 10, 2015 at 23:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.