| 学习路线指引(点击解锁) | 知识定位 | 人群定位 |
|---|---|---|
| 李 Python实战微信订餐小程序 李 | 进阶级 | 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。 |
| Python量化交易实战 | 入门级 | 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统 |
我们知道在springboot中有默认的json解析器,Spring Boot 中默认使用的 Json 解析技术框架是 jackson。我们点开 pom.xml 中的 spring-boot-starter-web 依赖,可以看到一个 spring-boot-starter-json依赖:
引入依赖
其实引不引入这个依赖都一样 spring-boot-starter-web 里面就包含这个依赖
就是为了让你们理解是这个依赖在发挥作用
xml
com.fasterxml.jackson.datatypegroupId>
jackson-datatype-jsr310artifactId>
dependency>
配置全局生效
- Configuration 标记这是配置类 @Bean注入到spring容器中 @value 获取参数
- 这里配置的格式化日期格式是全局生效 yyyy-MM-dd HH:mm:ss
- 这里给依赖全路径 方便导包
java
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class LocalDateTimeSerializerConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
// 默认LocalDateTime格式化的格式 yyyy-MM-dd HH:mm:ss
return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
}
}
**实体类 **
日期类型是 LocalDateTime
Less
@Data
@EqualsAndHashCode(callSuper = false)
@TableName(value = "sg_article")
public class Article implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField(value = "title")
private String title;
@TableField(value = "content")
private String content;
@TableField(value = "summary")
private String summary;
@TableField(value = "category_id")
private Long categoryId;
@TableField(exist = false)
private String categoryName;
@TableField(value = "thumbnail")
private String thumbnail;
@TableField(value = "is_top")
private String isTop;
@TableField(value = "status")
private String status;
@TableField(value = "view_count")
private Long viewCount;
@TableField(value = "is_comment")
private String isComment;
@TableField(value = "create_by")
private Long createBy;
@TableField(value = "create_time")
private LocalDateTime createTime;
@TableField(value = "update_by")
private Long updateBy;
@TableField(value = "update_time")
private LocalDateTime updateTime;
@TableField(value = "del_flag")
private Integer delFlag;
}
接口测试结果
1 在没有加全局日期格式化配置文件的时候
2 加了全局配置类的时候
3 指定某个字段解析规则yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
java
@TableField(value = "create_time")
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDateTime createTime;
常用场景
- 我们一般会配置全局解析的规则 这样方便后续对于时间格式的处理 默认的格式 按照国人的喜好 不太方便 对于后面日期格式个性的要求 我们可以针对某个属性去设置解析规则
推荐】一下。



