在项目中从redis获取带有LocalDateTime类型属性的对象时出现了以下异常:
org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Can not construct instance of java.time.LocalDateTime: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
......
......
这是因为我们将数据存入redis时,Jackson默认将LocalDateTime类型序列化为以下形式:
"createTime": {
"dayOfYear":141,
"dayOfWeek":"WEDNESDAY",
"month":"MAY",
"dayOfMonth":20,
"year":2020,
"monthValue":5,
"hour":19,
"minute":50,
"second":47,
"nano":364000000,
"chronology":{
"calendarType":"iso8601",
"id":"ISO"
}
}
我们从redis获取数据,Jackson反序列化LocalDateTime类型时出错,无法进行反序列化,就报了上面的异常。
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatypegroupId>
<artifactId>jackson-datatype-jsr310artifactId>
dependency>
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
@JsonSerialize(using = LocalDateTimeSerializer.class)
添加注解之后的序列化结果:[2020,5,14,10,25,19,494000000]
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
添加注解之后的反序列化结果:2020-05-14T10:25:19.494
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
格式化之后:
序列化结果:2020-05-14 10:30:17
反序列化结果:2020-05-14T10:30:17
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "激活时间")
private LocalDateTime activeTime;
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatypegroupId>
<artifactId>jackson-datatype-jsr310artifactId>
dependency>
CommonConstant.interface
public interface CommonConstant {
ObjectMapper JacksonMapper = new ObjectMapper()
.registerModule(new JavaTimeModule());
}
通过CommonConstant.JacksonMapper.writeValueAsString(object)将对象序列化之后存入redis
redisService.putHash(key, hashKey,
CommonConstant.JacksonMapper.writeValueAsString(device));
String result = (String) redisService.getHash(
key, hashKey);
Device device = CommonConstant.JacksonMapper
.readValue(result, Device.class);