解决Jackson2反序列化LocalDateTime报错
程序员文章站
2022-03-18 15:42:21
今天在整合redis和spring boot的时候,遇到了一个错误,记录一下。 报错如下: Could not read JSON: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default c ......
今天在整合redis和spring boot的时候,遇到了一个错误,记录一下。
报错如下:
could not read json: cannot construct instance of `java.time.localdatetime` (no creators, like default construct, exist): cannot deserialize from object value (no delegate- or property-based creator)
查看后发现是数据从redis中取出时,jackson2反序列化数据处理localdatetime类型时出错,原因是:jackson2在序列化localdatetime时输出的不是普通的字符串时间格式,而是如下所示的格式(普通时间格式:2019-02-27 12:10:17)
{ "date": { "year": 2019, "month": "february", "day": 27, "dayofmonth": 27, "dayofweek": "wednesday", "era": [ "java.time.chrono.isoera", "ce" ], "dayofyear": 58, "leapyear": false, "chronology": { "id": "iso", "calendartype": "iso8601" }, "prolepticmonth": 24229, "monthvalue": 2 }, "time": { "hour": 12, "minute": 10, "second": 17, "nano": 0 }, "month": "february", "year": 2019, "dayofmonth": 27, "dayofweek": "wednesday", "dayofyear": 58, "hour": 12, "minute": 10, "nano": 0, "second": 17, "monthvalue": 2, "chronology": [ "java.time.chrono.isochronology", { "id": "iso", "calendartype": "iso8601" } ] }
所以是jackson2序列化localdatetime跟我们所预想的不一致,将注册给redis的序列化模板修改成以下就行
1 @configuration 2 public class redisconfig { 3 4 /** 5 * 定义 userredistemplate ,指定序列化和反序列化的处理类 6 * 7 * @param factory redis连接工厂 8 * @return 模板 9 */ 10 @bean("userredistemplate") 11 public redistemplate<string, user> userredistemplate(redisconnectionfactory factory) { 12 redistemplate<string, user> template = new redistemplate<>(); 13 template.setconnectionfactory(factory); 14 jackson2jsonredisserializer<user> j2jrs = new jackson2jsonredisserializer<>(user.class); 15 objectmapper om = new objectmapper(); 16 om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any); 17 // 解决jackson2无法反序列化localdatetime的问题 18 om.disable(serializationfeature.write_dates_as_timestamps); 19 om.registermodule(new javatimemodule()); 20 om.enabledefaulttyping(objectmapper.defaulttyping.non_final, jsontypeinfo.as.property); 21 j2jrs.setobjectmapper(om); 22 // 序列化 value 时使用此序列化方法 23 template.setvalueserializer(j2jrs); 24 template.sethashvalueserializer(j2jrs); 25 // 序列化 key 时 26 stringredisserializer srs = new stringredisserializer(); 27 template.setkeyserializer(srs); 28 template.sethashkeyserializer(srs); 29 template.afterpropertiesset(); 30 return template; 31 } 32 }
主要是加上标红的那两句
参考文档:
genericjackson2jsonredisserializer 反序列化问题
上一篇: mvp模式
下一篇: Python 描述符是什么?以及如何实现