Jackson set global date format for all Date fields

Viewed 2689

I am working on non spring boot project.

There are plenty of data objects and it is starting to get inconvenient to annotate all date fields with JsonFormat.

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = JacksonSerialiser.DATE_FORMAT)
private Date someDate;

I know I can set date format directly on the ObjectMapper

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
OBJECT_MAPPER.setDateFormat(simpleDateFormat);

This works if all serialization/deserialization is done directly using the object mapper.

You could implement CustomDateSerializer by extending StdSerializer<Date>, but again in order for the format to be applied you need to specify this on field level like so:

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

With spring boot there is property you can use:

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

Would be great if I can set such property without spring.

1 Answers

One option is to implement your own Jackson2ObjectMapperBuilderCustomizer and expose it as a bean. Then you can put your date transformation customizations there with a custom serializer and deserializer. Then the default object mapper will have your customization and everything downstream will automatically inherit from it.

Related example How to customise Jackson in Spring Boot 1.4

Related