【Java+Jackson工具】converValue日期类型字段(properties)转换失败,字段properties转换失败问题
问题背景
下面这段代码
ObjectMapper objectMapper = new ObjectMapper();
List<UserInfoVO> userInfoList = objectMapper.convertValue(dataList, new TypeReference<List<UserInfoVO>>() {
});
有两个exception
一个是字段properties转换exception
java.lang.IllegalArgumentException: Unrecognized field "CAlipay" (class com.abc.abcsvc.vo.UserInfoVO), not marked as ignorable
一个是日期类型字段转换exception
java.lang.IllegalArgumentException: Cannot construct instance of java.time.LocalDateTime (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2025-07-04') at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: java.util.ArrayList[0]-
这个代码的逻辑是获取JSON之后转换成对象
对应报错的JSON字符串如下(省略非必要信息)
{ "batchNo": 20000000000000, "totalNum": 1, "dataList": [ { "CAlipay": "12344", "issueDate": "2000-01-01" } ] }
原因
使用的是springboot进行开发,内置的jackson依赖默认字段映射是大小写敏感的、且不支持java时间类(没了解过最新版是否支持)
解决办法
显式声明大小写不敏感
将java时间接口注册上objectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) // 显式声明大小写不敏感
.registerModule(new JavaTimeModule());// 将java时间接口注册上objectMapper
List<UserInfoVO> userInfoList = objectMapper.convertValue(dataList, new TypeReference<List<UserInfoVO>>() {
});

浙公网安备 33010602011771号