Formatting Java Time with Spring Boot using JSON

stf0-banner 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 into five steps. Each step represents one aspect of the issue and it is also related to one commit in the 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.

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":{  
        "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.

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

com.fasterxml.jackson.datatype
      jackson-datatype-jsr310

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

{  
    "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 be 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:

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

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

{  
    "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 the 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.

@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:

{  
    "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 the 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

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:

public class LocalDateSerializer extends JsonSerializer {
    
    @Override
    public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(value.format(FORMATTER));
    }
}
    
public class LocalDateDeserializer extends JsonDeserializer {
    
    @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:

{  
    "localDate":"01::01::2016"
}

Tests

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

@Configuration
public class RestTemplateFactory {
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Bean
    public RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        List 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.

Blog from Michał Lewandowski personal blog. Photo Credit.

You May Also Like

Grails session timeout without XML

This article shows clean, non hacky way of configuring featureful event listeners for Grails application servlet context. Feat. HttpSessionListener as a Spring bean example with session timeout depending on whether user account is premium or not.

Common approaches

Speaking of session timeout config in Grails, a default approach is to install templates with a command. This way we got direct access to web.xml file. Also more unnecessary files are created. Despite that unnecessary files are unnecessary, we should also remember some other common knowledge: XML is not for humans.

Another, a bit more hacky, way is to create mysterious scripts/_Events.groovy file. Inside of which, by using not less enigmatic closure: eventWebXmlEnd = { filename -> ... }we can parse and hack into web.xml with a help of XmlSlurper.
Even though lot of Grails plugins do it similar way, still it’s not really straightforward, is it? Besides, where’s the IDE support? Hello!?

Examples of both above ways can be seen on StackOverflow.

Simpler and cleaner way

By adding just a single line to the already generated init closure we have it done:
class BootStrap {

def init = { servletContext ->
servletContext.addListener(OurListenerClass)
}
}

Allrighty, this is enough to avoid XML. Sweets are served after the main course though :)

Listener as a Spring bean

Let us assume we have a requirement. Set a longer session timeout for premium user account.
Users are authenticated upon session creation through SSO.

To easy meet the requirements just instantiate the CustomTimeoutSessionListener as Spring bean at resources.groovy. We also going to need some source of the user custom session timeout. Let say a ConfigService.
beans = {    
customTimeoutSessionListener(CustomTimeoutSessionListener) {
configService = ref('configService')
}
}

With such approach BootStrap.groovy has to by slightly modified. To keep control on listener instantation, instead of passing listener class type, Spring bean is injected by Grails and the instance passed:
class BootStrap {

def customTimeoutSessionListener

def init = { servletContext ->
servletContext.addListener(customTimeoutSessionListener)
}
}

An example CustomTimeoutSessionListener implementation can look like:
import javax.servlet.http.HttpSessionEvent    
import javax.servlet.http.HttpSessionListener
import your.app.ConfigService

class CustomTimeoutSessionListener implements HttpSessionListener {

ConfigService configService

@Override
void sessionCreated(HttpSessionEvent httpSessionEvent) {
httpSessionEvent.session.maxInactiveInterval = configService.sessionTimeoutSeconds
}

@Override
void sessionDestroyed(HttpSessionEvent httpSessionEvent) { /* nothing to implement */ }
}
Having at hand all power of the Spring IoC this is surely a good place to load some persisted user’s account stuff into the session or to notify any other adequate bean about user presence.

Wait, what about the user context?

Honest answer is: that depends on your case. Yet here’s an example of getSessionTimeoutMinutes() implementation using Spring Security:
import org.springframework.security.core.context.SecurityContextHolder    

class ConfigService {

static final int 3H = 3 * 60 * 60
static final int QUARTER = 15 * 60

int getSessionTimeoutSeconds() {

String username = SecurityContextHolder.context?.authentication?.principal
def account = Account.findByUsername(username)

return account?.premium ? 3H : QUARTER
}
}
This example is simplified. Does not contain much of defensive programming. Just an assumption that principal is already set and is a String - unique username. Thanks to Grails convention our ConfigService is transactional so the Account domain class can use GORM dynamic finder.
OK, config fetching implementation details are out of scope here anyway. You can get, load, fetch, obtain from wherever you like to. Domain persistence, principal object, role config, external file and so on...

Any gotchas?

There is one. When running grails test command, servletContext comes as some mocked class instance without addListener method. Thus we going to have a MissingMethodException when running tests :(

Solution is typical:
def init = { servletContext ->
if (Environment.current != Environment.TEST) {
servletContext.addListener(customTimeoutSessionListener)
}
}
An unnecessary obstacle if you ask me. Should I submit a Jira issue about that?

TL;DR

Just implement a HttpSessionListener. Create a Spring bean of the listener. Inject it into BootStrap.groovy and call servletContext.addListener(injectedListener).