Search code examples
javajsonvert.xobjectmapperjsonobjectrequest

Object mapper removing empty and null values when converting object to string Java


In response to api call, i'm sending Json Class Object as response.

I need response like this without empty objects being removed.

{
   "links": {
      "products": [],
     "packages": []
    },
   "embedded":{
      "products": [],
      "packages": []
    }
}

but final Response is looking like this

{
 "links": {},
 "embedded": {}
}

Solution

  • Two things to be aware of:

    1. null and empty are different things.
    2. AFAIK Jackson is configured to serialize properties with null values by default.

    Make sure to properly initialize your properties in your object. For example:

    class Dto {
        private Link link;
        private Embedded embedded;
        //constructor, getters and setters...
    }
    
    class Link {
        //by default these will be empty instead of null
        private List<Product> products = new ArrayList<>();
        private List<Package> packages = new ArrayList<>();
        //constructor, getters and setters...
    }
    

    Make sure your classes are not extending another class with this annotation @JsonInclude(JsonInclude.Include.NON_NULL). Example:

    //It tells Jackson to exclude any property with null values from being serialized
    @JsonInclude(JsonInclude.Include.NON_NULL)
    class BaseClass {
    }
    
    //Any property with null value will follow the rules stated in BaseClass
    class Dto extends BaseClass {
        private Link link;
        private Embedded embedded;
        //constructor, getters and setters...
    }
    
    class Link extends BaseClass {
       /* rest of the design */
    }
    

    If you have the latter and you cannot edit BaseClass then you can define different rules in the specific classes:

    class Link extends BaseClass{
    
        //no matter what rules are defined elsewhere, this field will be serialized
        @JsonInclude(JsonInclude.Include.ALWAYS)
        private List<Product> products;
        //same here
        @JsonInclude(JsonInclude.Include.ALWAYS)
        private List<Package> packages;
        //constructor, getters and setters...
    }