String转Date问题

x33g5p2x  于2022-03-31 转载在 其他  
字(2.4k)|赞(0)|评价(0)|浏览(578)

报错信息

  1. 未能将‘ java.lang.string’类型的属性值转换为‘ po.endtime’属性所需的类型‘ java.util.date’;
  2. 嵌套异常为 org.springwork.core.convert.convert.converversionfailedexception:
  3. 未能将[ java.lang.string ]类型转换为[@org ]类型。
  4. 值“2022-03-30”的
  5. springframework.format.annotation.datetimformat java.util.date; 嵌套异常是
  6. java.lang.illegalargumentexception: 值的解析尝试失败[2022-03-30]
  1. "JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2022-02-28T16:12:00.000Z": Failed to deserialize java.time.LocalDateTime:
  2. (java.time.format.DateTimeParseException) Text '2022-02-28T16:12:00.000Z' could not be parsed at index 10; nested exception is
  3. com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2022-02-28T16:12:00.000Z": Failed to
  4. deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-02-28T16:12:00.000Z' could not be parsed at index 10
  5. at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 171] (through reference chain:
  6. com.suzui.homework.entity.Homework["hbegindate"])"

加上@DateTimeFormat注解之后依然失败。

解决办法

使用fastjson替换springboot原本的jackson

添加依赖

编写配置类

配置类中需要注意设置的日期格式

  1. import com.alibaba.fastjson.serializer.SerializerFeature;
  2. import com.alibaba.fastjson.support.config.FastJsonConfig;
  3. import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.http.MediaType;
  6. import org.springframework.http.converter.HttpMessageConverter;
  7. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  8. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  9. import java.nio.charset.StandardCharsets;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. @Configuration
  13. @EnableWebMvc // 必须要有这个注解,否则报错
  14. public class WebConfig implements WebMvcConfigurer {
  15. @Override
  16. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  17. FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
  18. FastJsonConfig config = new FastJsonConfig();
  19. config.setCharset(StandardCharsets.UTF_8);
  20. config.setDateFormat("yyyy-MM-dd HH:mm:ssS");
  21. config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
  22. fastJsonConverter.setFastJsonConfig(config);
  23. List<MediaType> list = new ArrayList<>();
  24. list.add(MediaType.APPLICATION_JSON);
  25. fastJsonConverter.setSupportedMediaTypes(list);
  26. converters.add(fastJsonConverter);
  27. }
  28. }

相关文章