Handling JSON date format in Spring Boot
Spring Boot web often requires corresponding processing of the returned date format. The following lists three commonly used methods for processing date formats.
1. @JsonFormat
You need to add @JsonFormat annotation on each date attribute, which can be LocalDate or Date.
public class Contact { @JsonFormat(pattern="yyyy-MM-dd") private LocalDate birthday; @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Europe/Zagreb") private Date lastUpdate; }
This way you can get the following output:
{ "birthday": "2019-02-03", "lastUpdate": "2019-02-03 10:08:02" }
2. Configure the default format
The above method is to hardcode each date, but if most dates in the system need to adopt a certain format, it is most convenient to set them uniformly. You can add the following attributes to the configuration, and all dates will be converted into the corresponding format.
For individuals that require special processing, use annotations to configure them separately.
-format=yyyy-MM-dd HH:mm:ss -zone=Europe/Zagreb
3. Customize Jackson's ObjectMapper
In addition to using configuration, you can also use encoding, but configuration is definitely the most convenient. The encoding method is to be able to handle more personalized content. If it is just a configuration date, it is a bit overused.
@Configuration public class ContactAppConfig { private static final String dateFormat = "yyyy-MM-dd"; private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss"; @Bean public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() { return builder -> { (dateTimeFormat); (new LocalDateSerializer((dateFormat))); (new LocalDateTimeSerializer((dateTimeFormat))); }; } }
While this approach may seem a bit cumbersome, the benefit is that it works with Java 8 and traditional date types.
Summarize
The above are three commonly used ways to process dates in spring boot, just choose according to your needs.
These are just personal experience. I hope you can give you a reference and I hope you can support me more.