jackson反序列化問題
今天在將jackson轉為的字符串重新轉回對象的時候,異常了
Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string.
看下面一行,說是其中一個字段轉換失敗 private LocalDateTime createTime;
開始以為是jackson配置的原因:https://www.cnblogs.com/niceboat/p/7284099.html
試了之后發現無效,就看了一下jackson之前序列化的字符串,發現 createTime轉換的內容有點不對勁
"createTime": {
"year": 2020,
"monthValue": 3,
"month": "MARCH",
"dayOfMonth": 24,
"dayOfYear": 84,
"dayOfWeek": "TUESDAY",
"hour": 17,
"minute": 52,
"second": 31,
"nano": 0,
"chronology": { "calendarType": "iso8601", "id": "ISO" }
},
這什么鬼格式啊,明明返回給前端的時候不是這個樣子的,是很正常的時間格式 2020-03-24 17:52:31
。
研究之后發現,我的框架是SpringBoot,其中集成的jackson已經被我配置了關於LocalDateTime 的處理,所以接口返回前端的時候沒有問題;但是項目中使用的時候,在序列化的時候是new ObjectMapper()
的,SpringBoot中的配置和新創建的不一樣,所以在序列化和反序列化的時候,對LocalDateTime 的處理完全不一樣導致的轉換失敗
解決方法
統一序列化、反序列化的方法,要么全部使用新創建的ObjectMapper,要么使用SpringBoot中配置了的(建議使用SpringBoot中的,畢竟一些配置還是很有必要的)
- 使用SpringBoot中的
@Autowired
private ObjectMapper objectMapper;
//若是在工具類中,這個類需要添加 @Component ,使其能夠被spring檢測到
或者獲取bean
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
private static ObjectMapper objectMapper = ac1.getBean("objectMapper",ObjectMapper.class);