3

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.

Borislav Stoilov
  • 3,247
  • 2
  • 21
  • 46
  • Spring does that magic for you because it creates a bean of `ObjectMapper` which is a singleton probably. So in a non-spring project you could create a static factory method or something like this, which you would call where you need to do the serialization/deserialization to obtain the configured object mapper with your custom serializer. – Michał Krzywański Mar 04 '20 at 14:53

1 Answers1

0

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

Joe W
  • 2,773
  • 15
  • 35
  • The guy said that he is not working on a spring boot project. I would hate to down-vote your suggestion, but you should answer in the context that the guy is asking. – Steve Storck Jan 05 '21 at 15:36
  • Check the edit and timestamp @SteveStorck – Joe W Jan 06 '21 at 16:03