简体   繁体   中英

Grails 2.4 named configuration for JSON not working

I can't use a specified named config to render object as JSON. What i'm doing wrong?

I defined a named config in Bootstrap.groovy init method

import com.appromocodes.Project
import com.appromocodes.Promocode
import grails.converters.JSON

class BootStrap {

    def init = { servletContext ->


        JSON.createNamedConfig('apiCheck', {
            JSON.registerObjectMarshaller(Promocode) { Promocode promocode ->
                def map= [:]
                map['code'] = promocode.code
                map['allowedUses'] = promocode.allowedUses
                map['customInfo'] = promocode.customInfo

                return map              
              }
        })

    }
    def destroy = {
    }
}

Then i have a classic controller (not REST, but simple controller):

import grails.converters.JSON

class ApiV1Controller {

def apiV1Service

    def check() {

        log.info("check");

        def resultMap = apiV1Service.checkPromocode(params.projectKey, params.code)


        if (resultMap.statusCode != ResponseStatus.PROMOCODE_USED) {
        }

        def p = Promocode.get(1)

        JSON.use('apiCheck', {
            render p as JSON
        })

    }

}

I would expect that invocation of check action would output only the three properties specified in apiCheck named config, instead i get all the bean properties and also the metaClass properties "class" and "id".

If i don't specify a named config, then JSON renders correctly the bean showing only three properties.

What is wrong? Is it possible to use namedConfig also in non REST controllers?

DefaultConverterConfiguration as JSON with default config is passed on to the closure as a parameter. That configuration has to be used to registerObjectMarshaller . So the closure has to be implemented as below (note the param to the closure).

JSON.createNamedConfig('apiCheck', { config ->
     config.registerObjectMarshaller(Promocode) { Promocode promocode ->
         def map= [:]
         map['code'] = promocode.code
         map['allowedUses'] = promocode.allowedUses
         map['customInfo'] = promocode.customInfo

         return map              
     }
})

An easier, clear and groovier implementation would be:

JSON.createNamedConfig( 'apiCheck' ) { 
     it.registerObjectMarshaller( Promocode ) { Promocode promocode ->
         [ 
             code        : promocode.code, 
             allowedUses : promocode.allowedUses,
             customInfo  : promocode.customInfo
         ]
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM