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.

3
  • Which version of grails? Mar 27, 2016 at 12:42
  • i am using Grails 2.5.1 Mar 27, 2016 at 12:47
  • Well what's the issue that you are getting when doing customMap as JSON? Mar 27, 2016 at 13:44

0

Your Answer

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

Browse other questions tagged or ask your own question.