How to set date format for JSON converter in Grails

社会主义新天地 提交于 2019-12-05 04:06:07

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.

Jeff Smith

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!