JSON.registerObjectMarshaller doesn't work in bootstrap

429 views Asked by At

When I want to test a customized "render as JSON " method, I used the following code

class BootStrap{
def init = { servletContext ->
 ....
 println "change the json before format"
 JSON.registerObjectMarshaller(Date) {
     println "JSON DATE MARSHAL"
     return it.format("yyyy-MM-dd HH:mm:ss")
     }
 println "change the json after format"
 }
}

but what printed in the console is like this:

| Compiling 1 source files

| Running Grails application

Active MQ start. ConsumerURL is failover:ssl://xxx.

change the json before format

change the json after format

|Server running. Browse to http://xxx

the strange thing is that the "JSON DATE MARSHAL"didn't be printed. But it worked when I put the code in a controller.

I don't know what happened.

Any suggestion will be appretiated.


Update: Like railsdog said, it seems the closure in the init didn't work.

What I supposed the date format in JSON is like this:2016-12-15 16:44:21

But what I get is 2016-12-15T08:44:21Z.

When I put the marshaller in controller, it worked, and the date format in JSON is as expected:

2016-12-15 16:44:21.

I also get the console output:"JSON DATE MARSHAL".

2

There are 2 answers

1
Michal_Szulc On

Instead of registering marshaller check out property grails.databinding.dateformats in your grails application config. You can add there more different date formats which should be handled by your app.

3
railsdog On

I would assume that registering the object marshaller doesn't actually execute/invoke the closure, hence no debug is emitted.