当我想测试自定义的“以JSON形式呈现”方法时,我使用了以下代码
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"
}
}
但是控制台上打印的内容是这样的:
| 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
奇怪的是没有打印“JSON DATE MARSHAL”。
但是,当我将代码放在 Controller 中时,它就起作用了。
我不知道发生了什么
任何建议将不胜感激。
更新:
就像railsdog所说的那样,似乎init中的关闭无效。
我认为JSON中的日期格式是这样的:2016-12-15 16:44:21
但是我得到的是2016-12-15T08:44:21Z。
当我将编码器放入 Controller 时,它可以工作,并且JSON中的日期格式符合预期:
2016-12-15 16:44:21。
我还获得了控制台输出:“JSON DATE MARSHAL”。
最佳答案
我假设注册对象编码器实际上并未执行/调用闭包,因此不会发出调试信息。
关于json - JSON.registerObjectMarshaller在 Bootstrap 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41184487/