如何在 Grails 中以 JSON 形式返回特定日期格式?
在 Grails 中,您可以使用 JSON 转换器在控制器中执行此操作:
render Book.list() as JSON
渲染结果为
[
{"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
然后结果将是本机 javascript 日期
[
{"id":1,
"class":"Book",
"author":"Stephen King",
"releaseDate":new Date(1194127343161),
"title":"The Shining"}
]
如果我想获取特定的 日期像这样的日期格式:
"releaseDate":"06-04-2007"
我必须使用“收集”,这需要大量输入:
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
有没有更简单的方法来做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个简单的解决方案:从 Grails 1.1 开始,转换器已被重写为更加模块化。 不幸的是我没有完成这方面的文档。 现在它允许注册所谓的 ObjectMarshallers(实现 org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller 接口的简单 Pogo/Pojo)。
为了实现您想要的输出,您可以通过这种方式在 BootStrap.groovy 中注册这样一个 ObjectMarshaller:
还有其他几种方法可以自定义转换器的输出,我会尽力尽快赶上文档。
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:
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.
或者您可以在日期级别本身工作。 这可能不完全是您想要的,但它可能会激发一个在整个应用程序中一致工作的解决方案的想法。
Or you could work at the Date level itself. This might not be exactly what you want but it could spark an idea for a solution that would work consistently across your whole app.