为什么Date对JSON密钥的序列化与对JSON值的序列化有所不同? [英] Why does Date serialize for a JSON key differently than it does for a JSON value?
问题描述
使用以下代码:
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"}
我期望键和值在同一日期具有相同的表示形式.
I was expecting the same representation as key and as value for the same date.
我可以强制JsonBuilder以与值相同的格式输出键吗?
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")格式化日期.
,我知道这不是您希望更改的内容.由于键"部分是使用 toString()
方法序列化的,因此您有两种解决方案:要么使用 [date.format("yyyy-MM-dd'T'HH:mm:ssZ):日期]
或使用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).
这篇关于为什么Date对JSON密钥的序列化与对JSON值的序列化有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!