How to return specific date format as JSON in Grails?

后端 未结 2 654
闹比i
闹比i 2021-01-30 23:32

In Grails, you can use the JSON converters to do this in the controller:

render Book.list() as JSON

The render result is

[
{\"i         


        
2条回答
  •  悲哀的现实
    2021-01-31 00:08

    There is a simple solution: Since Grails 1.1 the Converters have been rewritten to be more modular. Unfortunately I didn't finish the documentation for that. It allows now to register so called ObjectMarshallers (simple Pogo/Pojo's that implement the org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller interface).

    To achieve your desired output, you could register such an ObjectMarshaller in BootStrap.groovy that way:

    import grails.converters.JSON;
    
    class BootStrap {
    
         def init = { servletContext ->
             JSON.registerObjectMarshaller(Date) {
                return it?.format("dd-MM-yyyy")
             }
         }
         def destroy = {
         }
    }
    

    There are several other ways to customize the output of the Converters and I'll do my best do catch up with the documentation asap.

提交回复
热议问题