Search code examples
grailsgrails-2.0grails-controller

How can I register a custom json deserializer/parser in Grails?


Should I use filters or interceptors to meet the requirements, isn't there a simpler way?

UPDATE:
Looks like that my old code worked just fine, I've inadvertently edited the resources.groovy and invalidated the bean definition

resources.groovy
================

beans = {
    dateConverter DateConverter
}

BootStrap.groovy
================

class BootStrap {
    def grailsApplication

    def init = { servletContext ->
       def ctx = grailsApplication.mainContext
       def dataBinder = ctx.getBean(org.grails.databinding.SimpleDataBinder)
       dataBinder.conversionHelpers[Date] = [ctx.getBean('dateConverter')]
    }
 }

Solution

  • If you want to change it globally you can do something like this:

        class Foo {
            String name
        }
    

    and in Bootstrap.groovy (or whatever place you prefer):

        JSON.registerObjectMarshaller(Foo) {
            [name:it.name()]
        }
    

    If you need it only in special cases the easiest (in my experience) is to create a map and convert it to JSON

    [name:'foo'] as JSON
    

    Update

    @BindUsingdoes work for command objects too..

    class FooController {
        def foo (FooCmd bind) {
           render (text: "${bind.foo}")
        }
    }
    
    class FooCmd {
        @BindUsing({ obj, src ->
            "@BindUsing ${src['foo']}"
        })
        String foo
    }
    
    curl -i -H "Content-Type: application/json" -d '{"foo":"FOO!!!!"}' http://localhost:8080/Stackoverflow/Foo/foo