[JAVA] Serializing org.joda.time.DateTime to JSON in ISO 8601 format comes with milliseconds

// 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.

bonus

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

Serializing org.joda.time.DateTime to JSON in ISO 8601 format comes with milliseconds
Format JSON with org.json
Log output in Json format using lograge / lograge-sql with RubyOnRails
Convert ruby object to JSON format
Replace text in Excel file autoshapes with Apache POI
Getting Started with DBUnit
Serializing org.joda.time.DateTime to JSON in ISO 8601 format comes with milliseconds
Use thymeleaf3 with parent without specifying spring-boot-starter-parent in Spring Boot
Zip compression with Java in Windows environment without garbled characters
How to bind request parameters in list format with bean property in Spring
Output Spring Boot log in json format
Output Date in Java in ISO 8601 extended format
Working with huge JSON in Java Lambda
How to assemble JSON directly in Jackson
Convert JSON to TSV and TSV to JSON with Ruby
How to store an object in PostgreSQL as JSON with MyBatis (Mapper XML)
Jackson is unable to JSON serialize hibernateLazyInitializer in Spring Data JPA with error