0

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": {}
}
1
  • You need to show how you are preparing your response, and at which points it is complete, and at which points the attributes which are empty arrays are missing. Commented Dec 30, 2020 at 6:53

1 Answer 1

1

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...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.