Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set date format for JSON converter in Grails

I've a method in my Grails controller that should return a JSON, a property of the JSON is a Date object, but when I do:

render myObject as JSON

the output is like:

{
    "dateProperty": "2010-12-31T23:00:00Z",
    "otherProperty" : "aValue..."
}

Is there a way to change the default date format used from the converter?

I've tried to set the property grails.converters.json.date and also grails.date.formats in the Config.groovy, but this doesn't work.
Am I doing something wrong or is there another way to do it?

Thanks

like image 521
rascio Avatar asked Feb 05 '13 11:02

rascio


2 Answers

I generally use a custom Marshaller. Assume you have the following Domain

class Address { 
  String addressOne
  String city
  //bla bla
  Date dateCreated
}

Create a class under src/groovy like this

class AddressMarshaller {
  void register() {
     JSON.registerObjectMarshaller(Address) { Address address ->
      return [ 
         id: address.id,
         addressOne: address.addressOne,
         city: address.city,
         dateCreated: address.dateCreated.format('yyyy-MM-dd')
      ]
  }
}

Then in your Bootstrap file do the following:

[ new AddressMarshaller() ].each { it.register() }

The reason I do it as an array like that is because I have multiple marshallers.

Now, anytime you do address as JSON, you'll get the JSON you've described and you're correct date format. I know this seems like overkill for formatting a date in JSON but this has a lot of other benefits.

like image 71
Gregg Avatar answered Oct 21 '22 23:10

Gregg


If you want a default JSON marshaller for all Date types you can also use something very simple like shown in this SO answer. @Gregg's answer is a lot more flexible for individual domain classes.

like image 40
Jeff Smith Avatar answered Oct 21 '22 22:10

Jeff Smith