18.Cannot deserialize value of type `java.time.LocalDateTime` from String “2023-08-16 15:30:00“

项目报错

Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.LocalDateTime from String “2023-08-16 15:30:00”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2023-08-16 15:30:00’ could not be parsed at index 10
at [Source: UNKNOWN; line: -1, column: -1]

分析原因

实体属性类型为LocalDateTime,无法将字符串"2023-08-16 15:30:00"反序列化为java.time.LocalDateTime,即java不支持从字符串直接反序列化为LocalDateTime类;

解决办法

出参格式化:在实体类的LocalDateTime 类型的字段上加@JsonFormat注解即可;

//引入jsonFormat
import com.fasterxml.jackson.annotation.JsonFormat;		
public class CC{
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private LocalDateTime time;
}

扩展知识

1. 入参格式化:

(1)入参是实体对象,则在入参数实体类的LocalDateTime 类型的字段上加@DateTimeFormat注解 即可;
(2)入参是LocalDateTime字段,则在此字段之前上加@DateTimeFormat注解即可;

//入参是CC对象
//引入 DateTimeFormat
import org.springframework.format.annotation.DateTimeFormat;
public class CC{
	//实践验证,如果用实体接收前端参数,去掉此注解参数也可以被接收,接口也能正常调用
	@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private LocalDateTime time;
}
//入参是LocalDateTime字段
@PostMapping("/importFile")
public Object importFile(
@ApiParam(name = "files", value = "Excel文件", required = true) @RequestParam("files") MultipartFile[] files, 
@ApiParam(name = "time", value = "时间") @RequestParam("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime time) {
//.....
}

2. springboot全局时间格式设置

在yml中做如下配置即可;注意:注解配置优先级高于全局配置;

spring:
#(1)出参格式化:相当于设置了全局的@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  jackson:
  # 格式化全局时间字段
    date-format: yyyy-MM-dd HH:mm:ss
  # 指定时间区域类型  
    time-zone: GMT+8
# (2)入参格式化:相当于设置了全局的@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  mvc:
    format:
  # 默认的格式是dd/MM/yyyy,除此外任何格式都会400异常
      date: yyyy-MM-dd HH:mm:ss

3. 常用pattern

时间格式LocalDateTime:yyyy-MM-dd HH:mm:ss
日期格式LocalDate:yyyy-MM-dd

你可能感兴趣的:(一,后端Java,java,开发语言)