spring boot Joda DateTime Serialisation

edge66 picture edge66 · Nov 14, 2014 · Viewed 22.5k times · Source

I'm trying to serialize Joda DateTime properties as ISO-8601 using Spring Boot v1.2.0.BUILD-SNAPSHOT Here is my very simple REST Application.

@RestController
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

    class Info{

       private DateTime dateTime;

        public Info(){
            dateTime = new DateTime();
        }
        public DateTime getDateTime() {
           return dateTime;
        }

        public void setDateTime(DateTime dateTime) {
           this.dateTime = dateTime;
        }
    }

    @RequestMapping("/info")
    Info info() {
        return new Info();
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
   public Module getModule(){
        return new JodaModule();
   }
}

The dateTime is being serialized as a timestamp e.g. {"dateTime":1415954873412} I've tried adding

@Bean
@Primary
public ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                false);
    return objectMapper;
}

but that didn't help either. So how do I configure Jackson in Spring Boot to serialize using the ISO-8601 format? BTW: I only added the following dependencies to my Gradle build

compile("joda-time:joda-time:2.4")
compile("org.jadira.usertype:usertype.jodatime:2.0.1")
compile("com.fasterxml.jackson.datatype:jackson-datatype-joda:2.4.2");

Answer

Phil Webb picture Phil Webb · Nov 18, 2014

Since you're using Spring Boot 1.2 you should be able to simply add the following to your application.properties file:

spring.jackson.serialization.write_dates_as_timestamps=false

This will give output in the form:

{
    "dateTime": "2014-11-18T19:01:38.352Z"
}

If you need a custom format you can configure the JodaModule directly, for example to drop the time part:

@Bean
public JodaModule jacksonJodaModule() {
    JodaModule module = new JodaModule();
    DateTimeFormatterFactory formatterFactory = new DateTimeFormatterFactory();
    formatterFactory.setIso(ISO.DATE);
    module.addSerializer(DateTime.class, new DateTimeSerializer(
        new JacksonJodaFormat(formatterFactory.createDateTimeFormatter()
            .withZoneUTC())));
    return module;
}