How to ignore empty lists in Jackson?
Assume you are building a service which pushes the data to the client in JSON format. The data includes some list of objects, sometimes it will available, sometimes it may not. Below is the sample object, which we are using to build the JSON data. I have 4 list properties in this, suppose if one of the list properties is empty, in the JSON format, it will have an empty array. If the client accepts the empty array well and good, if not, we need to exclude it from the payload we are sending.
public class ClientData {
@JsonIgnore
private Long orderId;
@JsonProperty("additional_info")
private AdditionalInfoDTO additionalInfoDTO;
@JsonProperty("deed_current")
private DeedCurrentDTO deedCurrent;
@JsonProperty("deeds_prior")
private List<DeedPriorDTO> deedsPrior;
@JsonProperty("judgments_and_liens")
private List<JudgementAndLienDTO> judgementAndLienDTOS;
@JsonProperty("mortgages")
private List<MortgageDTO> mortgages;
@JsonProperty("property_info")
private PropertyInfoDTO propertyInfoDTO;
@JsonProperty("report_base64_pdf")
private String reportBase64Pdf;
@JsonProperty("tax_data")
private List<TaxDataDTO> taxDataDTO;
}
Below is the JSON, built using the above class. I have excluded some of the properties, to make it simple. If you look at the attribute judgments and liens it has an empty array.
{
"additional_info": {
"notes": "ffdffdfd"
},
"deed_current": {
"document_number": "instrument",
"document_page": "page",
"document_book": "book",
"grantor_name": "grantor",
"grantee_name": "800",
"document_type": "Warranty Deed",
"recorded_date": "02/11/2020"
},
"deeds_prior": [
{
"document_number": "instrument",
"document_page": "page",
"document_book": "book",
"grantor_name": "123",
"grantee_name": "34",
"deed_type": "Warranty Deed",
"recorded_date": "02/11/2020"
}
],
"judgments_and_liens": [],
"mortgages": [
{
"amount": "6565656",
"document_book": "book",
"document_number": "instrument",
"document_page": "page",
"executed_date": "02/11/2020",
"grantee_name": "beneficiary",
"grantor_name": "grantor",
"recorded_date": "02/12/2020",
"document_type": "Mortgage"
}
]
}Let's see how to ignore the empty array in the JSON.
You can add @JsonInclude(JsonInclude.Include.NON_EMPTY), to the respective List properties.
@JsonProperty("deeds_prior")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<DeedPriorDTO> deedsPrior;
@JsonProperty("judgments_and_liens")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<JudgementAndLienDTO> judgementAndLienDTOS;
Also at the mapper level, you can do something like this.
//Convert the data into JSON string.
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
clientDataString = mapper.writeValueAsString(clientData);
This will remove the judgments_and_liens from the JSON.
Happy Programming...!!!
Comments
Post a Comment