首页 > 解决方案 > 将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

标签: javajsonserializationdeserializationobjectmapper

解决方案


原始类型intdouble不能表示null。使用包装类IntegerDouble可以表示空值。

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

推荐阅读