将HashMap反序列化为POJO并将空字段设置为null



我有一个JSON响应,我在其中解析为:

List<LinkedHashMap> jsonResponse = objectMapper.readValue(jsonResponse, List.class);

JSON响应以"{"开头,这就是为什么我必须将其反序列化为List类,并且嵌套在List中的是LinkedHashMaps,我不确定是否可以直接反序列化为我的自定义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

然后,当反序列化发生时,figure、max和offer被设置为0/0.0

基元类型intdouble不能表示null。使用可以表示null值的包装类IntegerDouble

public class ProductsByInstitiution {
private Integer id;
private Integer max;
private Double figure;
...
}

最新更新