// Groovy Version: 2.4.5 JVM: 1.8.0_77 Vendor: Oracle Corporation OS: Mac OS X
@Grab('com.fasterxml.jackson.core:jackson-core:2.8.5')
@Grab('com.fasterxml.jackson.datatype:jackson-datatype-joda:2.8.5')
@Grab('joda-time:joda-time:2.9.6')
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.util.ISO8601DateFormat
import com.fasterxml.jackson.datatype.joda.JodaModule
import org.joda.time.DateTime
def now = new DateTime()
def bean = new Bean(date1: now.toDate(), date2: now)
def objectMapper = new ObjectMapper()
.registerModule(new JodaModule())
.setDateFormat(new ISO8601DateFormat())
def json = objectMapper.writeValueAsString(bean)
println json
class Bean {
Date date1
DateTime date2
}
result
{
"date1": "2016-12-23T06:33:01Z",
"date2": "2016-12-23T06:33:01.045Z"
}
Date1
, which is java.util.Date
, does not have milliseconds.
It seems that you need to format it properly with @ com.fasterxml.jackson.annotation.JsonFormat
.
def objectMapper = new ObjectMapper()
.registerModule(new JodaModule())
// .setDateFormat(new ISO8601DateFormat())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
If you try it in the above state, date1
will also have milliseconds. The timezone specifier has also changed to + 0000
instead of Z
. ..
{
"date1": "2016-12-23T06:38:26.270+0000",
"date2": "2016-12-23T06:38:26.270Z"
}
Recommended Posts