- 報錯: No primary or default constructor found for class java.time.LocalTime
- 報錯: ailed to convert value of type ‘java.lang.String’ to required type 'java.tim
- 報錯: Could not read JSON: Cannot construct instance of
java.time.LocalTime(no Creators, like default c
解決辦法:
任意一個配置類中加上以下代碼,解決一些序列化問題:
@Bean
@Primary
public GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer() { ObjectMapper om = new ObjectMapper(); // 解決查詢緩存轉換異常的問題 om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 此項必須配置,否則會報java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); om.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true); // 支持 jdk 1.8 日期 ---- start --- om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); om.registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()) .registerModule(new ParameterNamesModule()); // --end -- GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(om); return genericJackson2JsonRedisSerializer; }
直接把導的依賴也發下吧:
// An highlighted block <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
1:Postman傳參,要選擇json、raw(不然你怎么修改時間數據都是參數格式失敗),LocalDate,LocalDateTime同理
2:實體類加上以下代碼,LocalDate,LocalDateTime同理
@DateTimeFormat(pattern = "HH:mm") @JsonFormat(pattern = "HH:mm")//這倆用了定義格式 @JsonDeserialize(using = LocalTimeDeserializer.class) @JsonSerialize(using = LocalTimeSerializer.class)、、這倆解決序列化問題,不然存redis會報錯
3:Controller請求參數,將LocalTime的字段放入實體類(可自建DTO),就可以解決,LocalDate,LocalDateTime同理
// @RequestBody(required = false)TimeSlotDto timeSlotDto
4:Controller請求LocalTime參數前,加上 @DateTimeFormat(pattern = “HH:mm”)
@RequestParam(required = false)。 LocalDate,LocalDateTime同理
// @RequestParam(required = false) @DateTimeFormat(pattern = "HH:mm")LocalTime startTime,@RequestParam(required = false) @DateTimeFormat(pattern = "HH:mm")LocalTime endTime
備注:
1、請求Controller的LocalTime前最好加上以下注解
@RequestBody(required = false)) @RequestParam(required = false))
2、swagger的配置中最好加上:.directModelSubstitute(LocalTime.class,String.class),以方便使用swagger測試。LocalDate,LocalDateTime同理。
附swagger配置文件:
@Bean
public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .directModelSubstitute(LocalTime.class,String.class)//就是加這一行!!! .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); }
