javajacksonjava-time

How to serialize LocalDateTime with Jackson?


I got the following piece of code:

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    String now = new ObjectMapper().writeValueAsString(new SomeClass(LocalDateTime.now()));
    System.out.println(now);

And I get this:

{"time":{"hour":20,"minute":49,"second":42,"nano":99000000,"dayOfYear":19,"dayOfWeek":"THURSDAY","month":"JANUARY","dayOfMonth":19,"year":2017,"monthValue":1,"chronology":{"id":"ISO","calendarType":"iso8601"}}}

What I want to achieve is a string in ISO8601

2017-01-19T18:36:51Z


Solution

  • This is probably due to mistake in your code. You were using new unconfigured instance of mapper, here is the fix:

     ObjectMapper mapper = new ObjectMapper();
     mapper.registerModule(new JavaTimeModule());
     mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
     String now = mapper.writeValueAsString(new SomeClass(LocalDateTime.now()));
     System.out.println(now);