依赖配置
<dependency><groupId>com.fasterxml.jackson.datatype</groupId><artifactId>jackson-datatype-jsr310</artifactId><version>2.9.8</version></dependency>
反序列化全局配置
import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.*;import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;import java.io.IOException;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.convert.converter.Converter;import org.springframework.util.StringUtils;/*** Converter 不可优化使用Lambda表达式,否则会出现启动失败的问题*/@Configurationpublic class LocalDateTimeSerializerConfig {/*** String --> LocalDate*/@Beanpublic Converter<String, LocalDate> localDateConverter() {return new Converter<String, LocalDate>() {@Overridepublic LocalDate convert(String source) {if (StringUtils.hasText(source)) {return LocalDate.parse(source, DateTimeFormatter.ISO_OFFSET_DATE);}return null;}};}/*** String --> LocalDatetime*/@Beanpublic Converter<String, LocalDateTime> localDateTimeConverter() {return new Converter<String, LocalDateTime>() {@Overridepublic LocalDateTime convert(String source) {if (StringUtils.hasText(source)) {return LocalDateTime.parse(source,DateTimeFormatter.ISO_OFFSET_DATE_TIME);}return null;}};}/*** String --> LocalTime*/@Beanpublic Converter<String, LocalTime> localTimeConverter() {return new Converter<String, LocalTime>() {@Overridepublic LocalTime convert(String source) {if (StringUtils.hasText(source)) {return LocalTime.parse(source, DateTimeFormatter.ISO_OFFSET_TIME);}return null;}};}/*** Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json*/@Beanpublic ObjectMapper objectMapper() {ObjectMapper objectMapper = new ObjectMapper();objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);// LocalDateTime系列序列化模块,继承自jsr310,我们在这里修改了日期格式JavaTimeModule javaTimeModule = new JavaTimeModule();javaTimeModule.addSerializer(LocalDateTime.class,new JsonSerializer<LocalDateTime>() {@Overridepublic void serialize(LocalDateTime value, JsonGenerator gen,SerializerProvider serializers)throws IOException {String format =value.atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);gen.writeString(format);}});javaTimeModule.addSerializer(LocalDate.class,new JsonSerializer<LocalDate>() {@Overridepublic void serialize(LocalDate value, JsonGenerator gen,SerializerProvider serializers)throws IOException {String format = value.format(DateTimeFormatter.ISO_OFFSET_DATE);gen.writeString(format);}});objectMapper.registerModule(javaTimeModule);return objectMapper;}}
注意 Converter
