How to return specific date format as JSON in Grails?

jackysee picture jackysee · Mar 27, 2009 · Viewed 14.2k times · Source

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

render Book.list() as JSON

The render result is

[
{"id":1,
 "class":"Book",
 "author":"Stephen King",
 "releaseDate":'2007-04-06T00:00:00',
 "title":"The Shining"}
]

You can control the output date by make a setting in Config.groovy

grails.converters.json.date = 'javascript' // default or Javascript

Then the result will be a native javascript date

[
{"id":1,
 "class":"Book",
 "author":"Stephen King",
 "releaseDate":new Date(1194127343161),
 "title":"The Shining"}
]

If I want to get a specific date format like this:

"releaseDate":"06-04-2007"

I have to use 'collect', which requires a lot of typing:

return Book.list().collect(){
  [
      id:it.id,
      class:it.class,
      author:it.author,
      releaseDate:new java.text.SimpleDateFormat("dd-MM-yyyy").format(it.releaseDate),
      title:it.title
  ]
} as JSON

Is there a simpler way to do this?

Answer

Siegfried Puchbauer picture Siegfried Puchbauer · Mar 29, 2009

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.