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?
To represent dates in JavaScript, JSON uses ISO 8601 string format to encode dates as a string. Dates are encoded as ISO 8601 strings and then treated just like a regular string when the JSON is serialized and deserialized.
There is no date format in JSON, there's only strings a de-/serializer decides to map to date values. However, JavaScript built-in JSON object and ISO8601 contains all the information to be understand by human and computer and does not relies on the beginning of the computer era (1970-1-1).
JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.
JSON does not directly support the date format and it stores it as String. However, as you have learned by now that mongo shell is a JavaScript interpreter and so in order to represent dates in JavaScript, JSON uses a specific string format ISODate to encode dates as string.
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.
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