Spring Boot (twelve): LocalDateTime formatting

After Java 8, the date class using Solution java.time packet corresponding LocalDateTime, LocalDate, LocalTime Class. (Reference Java8 new features)

 

In the Spring Boot (verify the version: 2.1.5.RELEASE), serialized format class date may not want to own, you need to define your own format. There are two ways to achieve.

 

1. annotation mode

Format are used @JsonFormat, @DateTimeFormat of defined sequence (the bean turn json) and anti sequence (JSON turn bean), such as

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime dateTime;

 

 

2. uniform configuration

Configuration define a class of objects ObjectMapper customize the specified date and the type of sequence corresponding to deserialize objects, such as

@Configuration
public class LocalDateTimeFormatConfig {
private static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
private static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";

@Bean
@Primary
public ObjectMapper objectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}

 

3. Summary

Notes ways need to be marked on each property, if the date is more class attribute more complicated, custom configuration class can be unified way of formatting to date. The case where both are present, in order to prevail notes that the notes will overwrite the unified configuration.

 


 

I welcome attention to the micro-channel public number, timely access to the latest share

Guess you like

Origin www.cnblogs.com/spec-dog/p/11865059.html