Formatting Java Time with Spring Boot using JSON

The aim of this post is to summarize and review ways of formatting Java Time objects using Spring Boot and Jackson library.

This post is organized in five steps. Each step represents one aspect of the issue and it is also related to one commit in example project repository.

Step 0 - Prerequirements

Versions and dependencies

This tutorial is based on Spring Boot version 1.3.1.RELEASE with spring-boot-starter-web. It uses jackson-datatype-jsr310 from com.fasterxml.jackson.datatype in version 2.6.4, which is a default version of Spring Boot. All of these is based on Java 8.

The Code

In the example code repository, you can find one HTTP service made with Spring Boot. This service is a GET operation, which returns a class with Java Time objects.
You can also find the integration test that deserializes the response.

Step 1 - The goal

I would like to return class Clock, containing LocalDate,LocalTime and LocalDateTime, preinitialized in constructor.

Clock - Service response class
1
2
3
4
5
6
public final class Clock {
private final LocalDate localDate;
private final LocalTime localTime;
private final LocalDateTime localDateTime;
...
}

Response class is serialized to JSON Map, which is a default behaviour. To some extent it is correct, but ISO formatted Strings in response are preferable.

LocalDate - response as JSON Map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{  
"localDate":{
"year":2016,
"month":"JANUARY",
"era":"CE",
"dayOfYear":1,
"dayOfWeek":"FRIDAY",
"leapYear":true,
"dayOfMonth":1,
"monthValue":1,
"chronology":{
"id":"ISO",
"calendarType":"iso8601"
}
}
}

Integration testing is an appropriate way to test our functionality.

Example of integration test
1
2
3
4
5
6
ResponseEntity<Clock> resp = sut.getForEntity("http://localhost:8080/clock", Clock.class);

assertEquals(OK, resp.getStatusCode());
assertEquals(c.getLocalDate(), resp.getBody().getLocalDate());
assertEquals(c.getLocalTime(), resp.getBody().getLocalTime());
assertEquals(c.getLocalDateTime(), resp.getBody().getLocalDateTime());

Unfortunately, tests are not passing, because of deserialization problems. The exception with message is thrown can not instantiate from JSON object.

Step 2 - Adds serialization

First things first. We have to add JSR-310 module. It is a datatype module to make Jackson recognize Java 8 Date & Time API data types.

Note that in this example jackson-datatype-jsr310 version is inherited from spring-boot-dependencies dependency management.

Dependency in pom.xml
1
2
3
4
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Response is now consistent but still, not perfect. Dates are serialized as numbers:

Dates serialized to numbers and integers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{  
"version":2,
"localDate":[
2016,
1,
1
],
"localTime":[
10,
24
],
"localDateTime":[
2016,
1,
1,
10,
24
],
"zonedDateTime":1451640240.000000000
}

We are one step closer to our goal. Tests are passing now because this format can deserialized without any additional deserializers.
How do I know?
Start an application server on commit Step 2 - Adds Object Mapper, then checkout to Step 1 - Introduce types and problems, and run integration tests without @WebIntegrationTest annotation.

Step 3 - Enables ISO formatting

ISO 8601 formatting is a standard. I’ve found it in many projects. We are going to enable and use it.
Edit spring boot properties file application.properties and add the following line:

application.properties file - disabling timestamps write
1
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

Now, the response is something that I’ve expected:

Dates serialized as Strings
1
2
3
4
5
6
7
{  
"version":2,
"localDate":"2016-01-01",
"localTime":"10:24",
"localDateTime":"2016-01-01T10:24",
"zonedDateTime":"2016-01-01T10:24:00+01:00"
}

Step 4 - Adds on demand formatting pattern

Imagine one of your client systems does not have a capability of formatting time. It may be a primitive device, or microservice that treats this date as a collection of characters. That is why special formatting is required.

We can change formatting in response class by adding JsonFormat annotation with pattern parameter. Standard SimpleDateFormat rules apply.

Using @JsonFormat annotation
1
2
3
4
5
@JsonFormat(pattern = "dd::MM::yyyy")
private final LocalDate localDate;

@JsonFormat(pattern = "KK:mm a")
private final LocalTime localTime;

Below there is a service response using custom @JsonFormat pattern:

Custom response style
1
2
3
4
5
6
7
{  
"version":2,
"localDate":"01::01::2016",
"localTime":"10:24 AM",
"localDateTime":"2016-01-01T10:24",
"zonedDateTime":"2016-01-01T10:24:00+01:00"
}

Our tests are still passing. It means that this pattern is used for serialization in service and deserialization in tests.

Step 5 - Globally changes formatting

There are situations where you have to resign from ISO 8601 formatting in your whole application, and apply custom made standards.

In this part, we will redefine format pattern for LocalDate. This will change formatting of LocalDate in every endpoint of your API.

We have to define:

  • DateTimeFormatter with our pattern.
  • Serializer using defined pattern.
  • Deserializer using defined pattern.
  • ObjectMapper bean with custom serializer and deserializer.
  • RestTemplate that uses our ObjectMapper.

Bean ObjectMapper is defined with annotation @Primary, to override default configuration.
My custom pattern for LocalDate is dd::MM::yyyy

Object mapper bean with custom pattern
1
2
3
4
5
6
7
8
9
10
11
12
13
14

public static final DateTimeFormatter FORMATTER = ofPattern("dd::MM::yyyy");

@Bean
@Primary
public ObjectMapper serializingObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}

Definitions of serializer and deserializer for all LocalDate classes:

Custom serializer and deserializer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LocalDateSerializer extends JsonSerializer<LocalDate> {

@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.format(FORMATTER));
}
}

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return LocalDate.parse(p.getValueAsString(), FORMATTER);
}
}

Now, the response is formatted with our custom pattern:

Formatted response
1
2
3
{  
"localDate":"01::01::2016"
}

Tests

When we define custom serializer, our tests start to fail. It is because RestTemplate knows nothing about our deserializer. We have to create custom RestTemplateFactory that creates RestTemplate with object mapper containing our deserializer.

Custom RestTemplateFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration
public class RestTemplateFactory {

@Autowired
private ObjectMapper objectMapper;

@Bean
public RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> converters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
jsonConverter.setObjectMapper(objectMapper);
converters.add(jsonConverter);
restTemplate.setMessageConverters(converters);
return restTemplate;
}
}

Conclusion

Custom formatting Dates is relatively simple, but you have to know how to set up it. Luckily, Jackson works smoothly with Spring. If you know other ways of solving this problem or you have other observations, please comment or let me know.

Photo credits: Banner, Thumbnail

Clojure - How to replace current time creation?

Recently, I’ve begun my adventure with Clojure programming language. As a result I’ve decided to share gathered knowledge and my opinion, in this and in few upcoming posts.

The problem

I had to implement algorithm that depends on the current date. Core information for this algorithm is number of days between current date and some date in the future, expressed in days.
Therefore, there is a call somewhere in the code:

Current time with Java 8
1
(. java.time.LocalDate now)

For the tests to be stable, I had to make sure that this call always return the same day.

Approach 1

I’ve decided to extract creation of the current date functionality to the function:

now-date function will return current time
1
(defn now-date [] (. java.time.LocalDate now))

During tests I’ve declared different function:

fixed-date function will return current time
1
(defn fixed-date [] (. java.time.LocalDate of 2015 01 28))

Passing function that creates a current date, solved the problem. It worked great, but it had the following disadvantages:

  • Passing to algorithm function that creates current time.
  • Using java notation (with dot) in Clojure.

Approach 2

Having a function, that returns a current time, I’ve decided to find a way of overwriting its definition in tests. I’ve found out that there is operation called with-redefs-fn, which allows re-defining the function temporarily in the local context. Having defined fixed-date function, block of code looks like this:

Replacing now-date with fixed-date
1
2
3
4
5
6
7
8
9
(deftest my-test
(with-redefs-fn { #'fixture/now-date fixed-date }
#(do
(testing "should work method a"
(let [result (fixture/do-stuff 30)]
(is (.equals 8.22M result))
))
;More tests
)))

fixture/now-date is a reference to function that I wanted to replace. This time I was amazed by language possibilities. But there was one more problem to solve. I did not want to use java notation.

Approach 3

There is a library called Clj-time. It wraps Joda Time library and makes Clojure code more friendly. I wanted to hold on Java 8 library, but I did not see any alternatives.

So I replaced (. java.time.LocalDate now) to (t/now) and also creation of fixed dates, and then I came up with an idea.

Approach 4

Maybe should I replace the Clj-time itself? My production code will be simpler and the test code will be simpler too!

Replacing t/now with fixed date
1
2
3
4
5
6
7
8
9
(deftest my-test
(with-redefs-fn { #'t/now #(t/date-time 2015 11 19) }
#(do
(testing "should work method a"
(let [result (fixture/do-stuff 30 1000)]
(is (.equals 8.22M result))
))
;More tests
)))

This is my final solution. I am still impressed how easily it that can be done.

I use Clojure for a week. If you have any other ideas how to solve this problem comment, let me know.

Photo credit: Vintage alarm clock, Thumbnail