使用以下代码:
def date = new Date() println new groovy.json.JsonBuilder([(date): date]).toString()结果是这样的
{"Fri Oct 28 15:00:45 ART 2016":"2016-10-28T18:00:45+0000"}我期待与同一日期的关键和价值相同的表示。
我可以强制JsonBuilder输出与值相同格式的键吗?
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?
最满意答案
事情是,JsonBuilder将默认使用new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")格式化日期,我知道这不是你想要改变的。 由于“key”部分是使用toString()方法序列化的,因此您有两种解决方案:使用[date.format("yyyy-MM-dd'T'HH:mm:ssZ"): date]或使用metaProgramming重载Date.toString() (它将用于每个Date对象,所以你可能不希望这样)。
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).
更多推荐
发布评论