java - 将HashMap反序列化为POJO并将空字段设置为null?
问题描述
我收到了一个 JSON 响应,我在其中解析如下:
List<LinkedHashMap> jsonResponse = objectMapper.readValue(jsonResponse, List.class);
JSON响应以'{'开头,这就是为什么我必须将其反序列化为List类,并且嵌套在List中的是LinkedHashMaps,我不确定是否可以直接反序列化为我的自定义POJO。我正在尝试将每个 HashMap 转换为我的自定义 POJO:
for (LinkedHashMap res : jsonResponse) {
ProductsByInstitution resObj = objectMapper.convertValue(res, ProductsByInstitution.class);
}
但是,此自定义 POJO 具有额外的可选字段,这些字段可能包含在 JSON 响应中,也可能不包含。最终发生的是 JSON 响应中排除的 Integer / Double 字段分别自动设置为 0 或 0.0。我希望它们为空。
编辑:
仍然收到空字段的 0。
我试过的代码:
TypeReference<List<ProductsByInstitution>> typeRef
= new TypeReference<List<ProductsByInstitution>>() {};
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
List<ProductsByInstitution> objs = objectMapper.readValue(lambdaResponse, typeRef);
最后一行是错误指向的位置。
POJO类:
public class ProductsByInstitiution {
private int id;
private String name;
private String status;
private int buy;
private int offer;
private int max;
private int min;
private double figure;
.... (Getters and setters)
因此 JSON 响应可能如下所示:
id: 0
name: "Place"
status: "Good"
buy: 50
min: 20
然后当反序列化发生时,图、最大值和报价被设置为 0 / 0.0
解决方案
原始类型int
或double
不能表示null
。使用包装类Integer
或Double
可以表示空值。
public class ProductsByInstitiution {
private Integer id;
private Integer max;
private Double figure;
...
}
推荐阅读
- swift - 广泛的 Swift 扩展协议
- php - mkdir 无法处理文件夹内的 php
- c# - 如何使用 BFS 在 6x6 网格迷宫 C# 中找到最短路径
- reactjs - Store.subscribe:TypeError:__webpack_require__.i(...) 不是函数
- symfony - LexikJWTAuthenticationBundle 始终通过令牌存储获取空用户
- r - R - 替换正则表达式匹配的最后一个实例以及之后的所有内容
- javascript - 如何获取 Angular 2 中 div 中所有元素的引用?
- javascript - 使用 jQuery 在提交时显示/隐藏表单
- java - Java GUI Temp Calculator W/Two JButtons (Cel/Fah) Jlabel5 中的 Calc 输出?
- tensorflow - 激活函数的选择