1

I have registered named config in Bootstrap.groovy for my domain class "User" and "Role" as i want only the two required field to be rendered in 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
                ]
            }
        }
    }
//.. 

I want to render the objects of User Domain along with some other objects as 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
}
//..

i am getting response like.

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

But expected result is

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

Please help me in rendering the desired json. I have used JSON.registerObjectMarshaller but this will be a issue because it will be applicable for whole application which will be a issue.

Please suggest me how to solve this issue.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Shashank.gupta40
  • 915
  • 1
  • 8
  • 26

0 Answers0