Search code examples
javajsonserializationdeserializationobjectmapper

Deserializing a HashMap into a POJO and setting empty fields to null?


I have a JSON response coming in which I parse as such:

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

The JSON response begins with a '{', which is why I have to deserialize it into a List class, and nested in the List are LinkedHashMaps, which I'm not sure if I can directly deserialize into my custom POJO. I'm attempting to convert each HashMap to my custom POJO here:

        for (LinkedHashMap res : jsonResponse) {
            ProductsByInstitution resObj = objectMapper.convertValue(res, ProductsByInstitution.class);
        }

But, this custom POJO has extra optional fields which may or may not be included in the JSON response. What ends up happening is the Integer / Double fields excluded in the JSON response are automatically set to 0 or 0.0, respectively. I want them to be null.

EDIT:

Still receiving 0's for empty fields.

Code I tried:

        TypeReference<List<ProductsByInstitution>> typeRef
                = new TypeReference<List<ProductsByInstitution>>() {};
        objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        List<ProductsByInstitution> objs = objectMapper.readValue(lambdaResponse, typeRef);

The last line is where the error is pointing to.

POJO class:

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)

So a JSON response might look like this:

id: 0
name: "Place"
status: "Good"
buy: 50
min: 20

Then when deserialization happens, figure, max, and offer are being set to 0 / 0.0


Solution

  • Primitive type int or double can't represent null. Use wrapper class Integer or Double which can represent null value.

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