I just released Module 10 in the Master Class of “REST with Spring”:

>> THE "REST WITH SPRING" CLASSES

1. Overview

In this tutorial, we’ll serialize dates with Jackson. We’ll start by serializing a simple java.util.Date, then Joda-Time as well as the Java 8 DateTime.

2. Serialize Date with Jackson

First – let’s see how to serialize a simple java.util.Date with Jackson.

In the following example – we will serialize an instance of “Event” which has a Date field “eventDate“:

@Test
public void whenSerializingDateWithJackson_thenSerializedToTimestamp()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date date = df.parse("01-01-1970 01:00");
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValueAsString(event);
}

What’s important here is that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).

The actual output of the “event” serialization is:

{
   "name":"party",
   "eventDate":3600000
}

3. Serialize Date to ISO-8601

Clearly serializing to this terse timestamp format is not optimal. Let’s now serialize the Date to the ISO-8601 format:

@Test
public void whenSerializingDateToISO8601_thenSerializedToText()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    String toParse = "01-01-1970 02:30";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    mapper.setDateFormat(new ISO8601DateFormat());
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("1970-01-01T02:30:00Z"));
}

Note how the representation of the date is now much more readable.

4. Configure ObjectMapper DateFormat

The previous solutions still lack the full flexibility of choosing the exact format to represent the java.util.Date instances.

Let’s now take a look at a configuration that will allow us to set our own formats for representing dates:

@Test
public void whenSettingObjectMapperDateFormat_thenCorrect()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");

    String toParse = "20-12-2014 02:30";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(df);

    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString(toParse));
}

Note that, even though we’re now more flexible in terms of the date format – we’re still using a global configuration at the level of the entire ObjectMapper.

5. Use @JsonFormat to format Date

Next, let’s take a look at the @JsonFormat annotation to control the date format on individual classes instead of globally, for the entire application:

public class Event {
    public String name;

    @JsonFormat
      (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    public Date eventDate;
}

Now – let’s test it:

@Test
public void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    String toParse = "20-12-2014 02:30:00";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString(toParse));
}

6. Custom Date Serializer

Next – to get full control over the output, we’ll leverage a custom serializer for Dates:

public class CustomDateSerializer extends StdSerializer<Date> {
 
    private SimpleDateFormat formatter 
      = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    public CustomDateSerializer() {
        this(null);
    }

    public CustomDateSerializer(Class t) {
        super(t);
    }
    
    @Override
    public void serialize (Date value, JsonGenerator gen, SerializerProvider arg2)
      throws IOException, JsonProcessingException {
        gen.writeString(formatter.format(value));
    }
}

Next – let’s use it as the serializer of our “eventDate” field:

public class Event {
    public String name;

    @JsonSerialize(using = CustomDateSerializer.class)
    public Date eventDate;
}

Finally – let’s test it:

@Test
public void whenUsingCustomDateSerializer_thenCorrect()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    String toParse = "20-12-2014 02:30:00";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString(toParse));
}

7. Serialize Joda-Time with Jackson

Dates aren’t always an instance of java.util.Date; actually – they’re more and more represented by some other class – and a common one is, of course, the DateTime implementation from the Joda-Time library.

Let’s see how we can serialize DateTime with Jackson.

We’ll make use of the jackson-datatype-joda module for out of the box Joda-Time support:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.4.0</version>
</dependency>

And now we can simply register the JodaModule and be done:

@Test
public void whenSerializingJodaTime_thenCorrect() 
  throws JsonProcessingException {
    DateTime date = new DateTime(2014, 12, 20, 2, 30, 
      DateTimeZone.forID("Europe/London"));

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String result = mapper.writeValueAsString(date);
    assertThat(result, containsString("2014-12-20T02:30:00.000Z"));
}

8. Serialize Joda DateTime with Custom Serializer

If we don’t want the extra Joda-Time Jackson dependency – we can also make use of a custom serializer (similar to the earlier examples) to get DateTime instances serialized cleanly:

public class CustomDateTimeSerializer extends StdSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
      DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

    public CustomDateTimeSerializer() {
        this(null);
    }

     public CustomDateTimeSerializer(Class<DateTime> t) {
         super(t);
     }
    
    @Override
    public void serialize
      (DateTime value, JsonGenerator gen, SerializerProvider arg2)
      throws IOException, JsonProcessingException {
        gen.writeString(formatter.print(value));
    }
}

Next – let’s use it as our property “eventDate” serializer:

public class Event {
    public String name;

    @JsonSerialize(using = CustomDateTimeSerializer.class)
    public DateTime eventDate;
}

Finally – let’s put everything together and test it:

@Test
public void whenSerializingJodaTimeWithJackson_thenCorrect() 
  throws JsonProcessingException {
 
    DateTime date = new DateTime(2014, 12, 20, 2, 30);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("2014-12-20 02:30"));
}

9. Serialize Java 8 Date with Jackson

Next – let’s see how to serialize Java 8 DateTime – in this example, LocalDateTime – using Jackson. We can make use of the jackson-datatype-jsr310 module:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>

Now, all we need to do is register the JSR310Module and Jackson will take care of the rest:

@Test
public void whenSerializingJava8Date_thenCorrect()
  throws JsonProcessingException {
    LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JSR310Module());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String result = mapper.writeValueAsString(date);
    assertThat(result, containsString("2014-12-20T02:30"));
}

10. Serialize Java 8 Date Without any Extra Dependency

If you don’t want the extra dependency, you can always use a custom serializer to write out the Java 8 DateTime to JSON:

public class CustomLocalDateTimeSerializer 
  extends StdSerializer<LocalDateTime> {

    private static DateTimeFormatter formatter = 
      DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    public CustomLocalDateTimeSerializer() {
        this(null);
    }
 
    public CustomLocalDateTimeSerializer(Class<LocalDateTime> t) {
        super(t);
    }
    
    @Override
    public void serialize(
      LocalDateTime value,
      JsonGenerator gen,
      SerializerProvider arg2)
      throws IOException, JsonProcessingException {
 
        gen.writeString(formatter.format(value));
    }
}

Next – let’s use the serializer for our “eventDate” field:

public class Event {
    public String name;

    @JsonSerialize(using = CustomLocalDateTimeSerializer.class)
    public LocalDateTime eventDate;
}

Now – let’s test it:

@Test
public void whenSerializingJava8DateWithCustomSerializer_thenCorrect()
  throws JsonProcessingException {
 
    LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("2014-12-20 02:30"));
}

11. Deserialize Date

Next – let’s see how to deserialize a Date with Jackson. In the following example – we deserialize an “Event” instance containing a date:

@Test
public void whenDeserializingDateWithJackson_thenCorrect()
  throws JsonProcessingException, IOException {
 
    String json = "{"name":"party","eventDate":"20-12-2014 02:30:00"}";

    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(df);

    Event event = mapper.readerFor(Event.class).readValue(json);
    assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
}

12. Custom Date Deserializer

Let’s also see how to use a custom Date deserializer; we’ll write a custom deserializer for the property “eventDate“:

public class CustomDateDeserializer extends StdDeserializer<Date> {

    private SimpleDateFormat formatter = 
      new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    public CustomDateDeserializer() {
        this(null);
    }

    public CustomDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser jsonparser, DeserializationContext context)
      throws IOException, JsonProcessingException {
        String date = jsonparser.getText();
        try {
            return formatter.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

Next – let’s use it as the “eventDate” deserializer:

public class Event {
    public String name;

    @JsonDeserialize(using = CustomDateDeserializer.class)
    public Date eventDate;
}

And finally – let’s test it:

@Test
public void whenDeserializingDateUsingCustomDeserializer_thenCorrect()
  throws JsonProcessingException, IOException {
 
    String json = "{"name":"party","eventDate":"20-12-2014 02:30:00"}";

    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    ObjectMapper mapper = new ObjectMapper();

    Event event = mapper.readerFor(Event.class).readValue(json);
    assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
}

13. Conclusion

In this extensive Date article, we looked at most relevant ways Jackson can help marshalli and unmarshall a date to JSON using a sensible format we have control over.

The implementation of all these examples and code snippets can be found in my GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

Go deeper into building a REST API with Spring:

>> CHECK OUT THE COURSE

  • Bill

    Eugen –

    Again, great information! Something that I have been trying to get a definitive answer on for awhile (and the topic is serialization):

    Spring MVC 4, I’m letting spring serialize my response body using @RestController. I’d like to use my own serialization. I see a lot of solutions from various sources for spring 3 but nothing for 4 and no consensus on the “right” solution. Would you be willing to weigh in?

    Thanks,

    Bill

    • Hey Bill,
      Sure – you can definitely use your own `ObjectMapper`, configured exactly how you want it. Check out the “Without Spring Boot” section here – that will allow you to jump in and customize it fully. Hope it helps. Cheers,
      Eugen.

      • Bill

        It does – thanks!

  • Kisna

    If I were to use the same entity for serialization and de-serialization, isn’t there an elegant way to specify just one annotation?

    I have also had use cases where customer would pass two different date formats (sometimes suppressing the time part or the timezone part) that needed to be handled gracefully?

    What about “strictness” in formats in the above case? Default date formats are not strict at all.

    • Hey Kisna,
      The answer to your first question depends on which of these solutions you actually use. If you’re thinking of a simple annotation, usually putting that annotation on the field itself will mean that Jackson is going to use it for both serialization and deserialization.
      Now, handling 2 different formats sounds like it would need the more flexible custom serializer / deserializer – and some manual checking of the format to get the right one.
      Finally, on the default date format, you definitely don’t have to use any default – you can specify your own and make it adhere to whatever you need your dates to look like.
      Hope it helps. Cheers,
      Eugen.

      • Kisna

        Sorry, the first question was invalid. Rest makes sense, there is no clean option.

  • Kisna

    Is there a clean way to deserialize old (<7.x) Java Dates with JODA using JODAModule() without a custom serializer/deserializer?

    • I haven’t tried to use the Joda module to work with plain dates – and I don’t think it’s supported. That module is specifically meant for joda-time support. That being said, hopefully you’ll be able to deserialize dates with plain Jackson and not need that particular module. Cheers,
      Eugen.

      • Kisna

        Yes, for the older Java dates, a custom serializer that leverages the efficient JODA API by caching date formats. Is there a good way to inject this JODA based serializer for the old java.util.Date class only instead of mentioning the serializer annotation so many times? Just trying to figure out a best practice to use JODA for all Dates..

  • Charles Li

    It is very useful, thanks!~

  • Ben Friedman

    Eugen, thank you for these good examples. Any chance you can show your import statements? Or use fully qualified types? For example, JsonParser is a class in Jackson and Spring Boot. I presume this usage is for Jackson, not Spring Boot, yes?

    • Hey Ben – yes, it’s the Jackson class. I usually don’t include the import statements, but in this case, if there’s confusion – it would make sense. But until I do – yes, that’s the right import here.
      Cheers,
      Eugen.

  • Olle Sundblad

    Off topic: Your static use of SimpleDateFormat is very dangerous, since DateFormats are not thread safe. See, for example: http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html

  • Arun Menon

    Thanks Eugen, As always very helpful.

  • Luis Trigueiros

    Hi I found this tutorials fantastic, but is there an example of using Jackson without having to annotate one’s domain layer ?
    Thank you.

    • Grzegorz Piwowarek

      Luis, if you do not want to “contaminate” your domain, consider using “mix-in”s. In this approach, you create a “mixin” class where you put all necessary annotations and domain gets untouched

      • Luis Trigueiros

        Thank you for the help, this is what I was looking for, 🙂