0

With the following code:

def date = new Date()
println new groovy.json.JsonBuilder([(date): date]).toString()

The result is something like

{"Fri Oct 28 15:00:45 ART 2016":"2016-10-28T18:00:45+0000"}

I was expecting the same representation as key and as value for the same date.

Can I force the JsonBuilder to output the keys with the same format as the values?

bdkosher
  • 5,753
  • 2
  • 33
  • 40
Fernando
  • 2,131
  • 3
  • 27
  • 46

1 Answers1

1

Thing is, JsonBuilder will format dates using by default a new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") and I understand this is not what you wish to change. Since the "key" part is serialized with the toString() method, you have two solutions: either use [date.format("yyyy-MM-dd'T'HH:mm:ssZ"): date] or use metaProgramming to overload Date.toString() (it will be used for every Date object, though, so you might not want that).

sensei
  • 621
  • 7
  • 13
  • Thanks for the solution. But why JsonBuilder use toString in a context and SimpleDateFormat in the other? Is there a reason? – Fernando Oct 29 '16 at 13:13
  • 1
    For keys (in key/value pairs), it simply uses the default string representation of the key object, which is commonly obtained with `toString()`, and there's no reason to treat `Date` values differently. But date _values_ in JSON should be formatted in a way javascript will be able to parse them (see http://stackoverflow.com/questions/10286204/the-right-json-date-format) and so JsonBuilder treats `Date` objects accordingly. – sensei Oct 29 '16 at 22:15