背景
新起一个SpringBoot项目,操作增删改查业务且入参和出参中含有LocalDateTime、LocalDate、LocalTime的序列化与反序列化问题。如在接收时间类型的参数时,报错: Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value '2020-12-12 00:00:00'; 而在返回给前端小朋友的LocalDateTime格式是数组格式的,让我们抓耳挠腮。 这些都是由于LocalDateTime没有合理的序列化和反序列化引起的问题。
-
序列化:把Java对象转换为字节序列的过程。
-
反序列化:把字节序列恢复为Java对象的过程。
解决方案
以k-v样式拼接在url的LocalDateTime参数反序列化
局部解决方案
加在参数字段上
@GetMapping("/test")
public CommonResult test(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) LocalDateTime time) {
System.out.println(time);
return CommonResult.success(time);
}
全局解决方案
@ControllerAdvice
public class ExceptionResolver {
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.registerCustomEdi