如何将Json Named config与其他域对象或Map中的值一起呈现为JSON Grails-2.5.1

时间:2016-03-27 11:23:30

标签: json grails gorm

我在Bootstrap.groovy中为我的域类“User”和“Role”注册了命名配置,因为我只希望在Grails 2.5.1中呈现两个必填字段。

BootStrap.groovy中

//..
    def init = { servletContext ->
        JSON.createNamedConfig('thinUser') {
            it.registerObjectMarshaller( User ) { User user ->
                return [
                    id: user.id,
                    name: user.name
                ]
            }
        }

        JSON.createNamedConfig('thinRole') {
            it.registerObjectMarshaller( Role) { Role role->
                return [
                    id: role.id,
                    name: role.name
                ]
            }
        }
    }
//.. 

我想将用户域的对象与其他一些对象一起呈现为Json。

UserController.groovy

//..
def createUser(){
  def customMap = [:]
  def userJson = JSON.use('thinUser') {
        User.list() as JSON
    }
      //println userJson  is giving appropriate result
      //[{"id":1,"name":"Peeyush"},{"id":2,"name":"Amit"}]

  customMap.users = userJson
  def roleJson =  JSON.use('thinRole') {
        Role.list() as JSON
    } 
  //println roleJson   is giving appropriate result

  customMap.roles = roleJson
  customMap.otherValue = 'someotherValue'
  customMap.userId = 1

  render customMap as JSON     // Having issue here unable to get expected result
}
//..

我得到的回应就像。

{"users":{"class":"grails.converters.JSON","depth":0,"writer":{"class":"org.codehaus.groovy.grails.web.json.JSONWriter"}}, .....}

但预期结果是

{"users":{{"id":1,"name":"Peeyush"},{"id":2,"name":"Amit"},{"id":3,"name":"Arpit"},{"id":4,"name":"Amit"}}, ....}

请帮我渲染所需的json。 我使用过JSON.registerObjectMarshaller,但这将是一个问题,因为它将适用于整个应用程序,这将是一个问题。

请建议我如何解决这个问题。

0 个答案:

没有答案