Grails: Defining a JSON custom marshaller as stati

2019-07-15 16:00发布

问题:

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?