【问题标题】:Deserializing a HashMap into a POJO and setting empty fields to null?将HashMap反序列化为POJO并将空字段设置为null?
【发布时间】:2020-07-27 14:59:27
【问题描述】:

我收到了一个 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

【问题讨论】:

  • Objectmapper 在反序列化 List.class 时使用链接的 hashmap。要使其成为某种类型的列表,您需要一个 TypeReference 示例,请参见:stackoverflow.com/questions/2525042/… 但如果是列表,只需使用:TypeReference>(并将 String 替换为实际类型)
  • 检查更新的 OP
  • 在 OP 中发布 POJO 代码

标签: java json serialization deserialization objectmapper


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-05-31
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多