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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With