项目场景:使用JSON将List转Map后发现null值被赋值为默认值:Double被赋值为0
Double被赋值为0
如下代码,在使用JSON转换为Map时,发现Double属性的值为null时,被默认处理为Integer 0
List<Map<String, Object>> res = targetList.stream()
.map(o -> JsonHelper.<String, Object>getMapByJson(JsonHelper.getJSONString(o)))
.collect(Collectors.toList());
原因分析:
查看JsonHelper.<String, Object>getMapByJson(JsonHelper.getJSONString(o))
DEFAULT_PARSER_FEATURE 是int类型,在加载过程会赋值为:0;
所以传值features = 0;
解决方案:
思路:使用自定义的映射函数来处理对象到
Map<String, Object>
的转换,同时确保不会改变null
值的类型。实现:使用Jackson库的
ObjectMapper
来处理JSON序列化和反序列化。ObjectMapper
是一个非常强大的工具,可以很好地处理各种数据类型,包括null
值。
具体代码:
public static void main(String[] args) throws Exception {
// 假设targetList是一个包含对象的列表
List<YourObject> targetList = ...;
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> res = targetList.stream()
.map(o -> convertToMapWithNullHandling(objectMapper, o))
.collect(Collectors.toList());
// 打印结果
res.forEach(System.out::println);
}
private static Map<String, Object> convertToMapWithNullHandling(ObjectMapper objectMapper, Object obj) {
try {
String jsonString = objectMapper.writeValueAsString(obj);
return objectMapper.readValue(jsonString, Map.class);
} catch (Exception e) {
throw new RuntimeException("Error converting object to map", e);
}
}
效果展示:改造后原值null值不会赋值为Integer:0