LocalDateTime与Spring Mvc、Lombok、Jackson的坑
坑1: Lombok的@Data + @Builder注解同时使用导致LocalDateTime无法格式化
如下接收参数实体类
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@Builder
public class CampusAntigenInfo implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "检测编号", example = "0124TESax15")
private String antigenDetectionNo;
@ApiModelProperty(value = "检测结果 0:阴性,1阳性,2无效", example = "0")
private Integer antigenDetectionType;
@ApiModelProperty(value = "检测地点 0:校内,1校外", example = "0")
private String antigenDetectionAddress;
@ApiModelProperty(value = "检测时间", example = "2022-05-10 09:25:41")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime antigenDetectionTime;
private String photoUrl;
}
当@Data和@Builder注解同时使用时:会导致无参构造丢失
Lombok的@Builder注解带来的两大坑
同时会导致时间类型字段格式化失败!
- 解决方案:添加无参+全参构造器注解
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CampusAntigenInfo implements Serializable {
..........
}
坑2: 使用@JsonForma无法格式化LocalDateTime
Jackson 默认不支持@JsonFormat格式化
- 方案1:需要引入 jsr310依赖
<!-- 解决localDateTime格式化问题 -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
- 方案2:使用@@DateTimeFormat
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime antigenDetectionTime;
坑3: LocalDateTime 格式化必须要有时分秒!
如
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDateTime antigenDetectionTime;
Spring Mvc 接口格式化时会报错!
- 一定要带时分秒!!!!
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime antigenDetectionTime;
- 如果没有时分秒使用 LocalDate
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDate antigenDetectionTime;