实践
代码(SpringBoot)
添加jackson依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.2</version> </dependency>
修改application.properties
###################################### #jackson.date-format ###################################### spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8
时间格式化配置类
package com.example.jsondemo; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.boot.jackson.JsonComponent; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.TimeZone; /** * @author CBeann * @create 2020-09-05 19:23 */ @Configuration @JsonComponent public class DateFormatConfig { @Value("${spring.jackson.date-format}") private String pattern; /** * @description date 类型全局时间格式化 * @date 2020-09-05 19:23 */ @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() { return builder -> { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat(pattern); df.setTimeZone(tz); builder.failOnEmptyBeans(false) .failOnUnknownProperties(false) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .dateFormat(df); }; } /** * @description LocalDate 类型全局时间格式化 * @date 2020-09-05 19:23 */ @Bean public LocalDateTimeSerializer localDateTimeDeserializer() { return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer()); } }
实体类
@Data public class Student { private String name; private Date date; private LocalDateTime localDateTime; private LocalDate localDate; private LocalTime localTime; }
测试
@RequestMapping("/hello") public Object jsonObject() { Student student = new Student(); student.setDate(new Date()); student.setLocalDate(LocalDate.now()); student.setLocalDateTime(LocalDateTime.now()); student.setLocalTime(LocalTime.now()); return student; }
测试结果
使用自定义格式
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
@Data public class Student { private String name; @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd") private Date date; @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd") private LocalDateTime localDateTime; private LocalDate localDate; private LocalTime localTime; }