报错内容
Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'xxxx';
 nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2021-10-03';
  nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2021-10-03]

当后端的实体类 使用jdk8的时间时,会报以上的问题
这个时候就需要使用 @DateTimeFormat(pattern = “yyyy-MM-dd”) 注解

该注解中的pattern 要和前端传过来的日期格式保持一致

如果是 LocalDateTime 可以使用 @DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)

这是反序列化时的做法,当序列化时 也就是后端传给前端时,转换时间格式使用 @JsonFormat(pattern = “yyyy-MM-dd”, timezone = “GMT+8”) 注解

	@DateTimeFormat(pattern = "yyyy-MM-dd")
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
	private LocalDate beginTime;

也可以设置全局

	@Bean
	@Primary
	@ConditionalOnMissingBean(ObjectMapper.class)
	public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
		ObjectMapper objectMapper = builder.createXmlMapper(false).build();
		// 全局配置序列化返回 JSON 处理
		SimpleModule simpleModule = new SimpleModule();
		//封装类型 Long ==> String
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
		simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
		simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
		simpleModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
		simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
		simpleModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
		objectMapper.registerModule(simpleModule);
		objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN));
		objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		return objectMapper;
	}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐