groovyjsonbuilder

Why does Date serialize for a JSON key differently than it does for a JSON value?


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?


Solution

  • 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).