Grails: Defining a JSON custom marshaller as static method in domain

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-14 19:21:27

问题


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?

来源:https://stackoverflow.com/questions/25280650/grails-defining-a-json-custom-marshaller-as-static-method-in-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!