如何在Grails中设置JSON转换器的日期格式 [英] How to set date format for JSON converter in Grails

查看:207
本文介绍了如何在Grails中设置JSON转换器的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Grails控制器中有一个方法应该返回一个JSON,JSON的属性是Date对象,但是当我这样做:

 将myObject渲染为JSON 

输出如下:

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

有没有办法更改使用的默认日期格式转换器?



我试图设置属性 grails.converters.json.date 还有code> grails.date.formats 在 Config.groovy 中,但这不起作用。

我做错了或是还有另一种做法吗?



谢谢

解决方案

我通常使用一个自定义的Marshaller。假设你有以下域名

  class Address {
String addressOne
String city
/ / bla bla
日期dateCreated
}

在src / groovy下创建一个类像这样

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

然后在Bootstrap文件中执行以下操作:

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

我这样做的一个数组的原因是因为我有多个编组。



现在,随着您以<地址作为JSON ,您将得到您所描述的JSON,并且您的日期格式正确。我知道这个格式在JSON格式化日期似乎是过分的,但这还有很多其他好处。


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.

这篇关于如何在Grails中设置JSON转换器的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆