- 报错: 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();
}