0

I am aware that in a Spring Boot project, I can filter out null valued attributes in response using @JsonInclude(JsonInclude.Include.NON_NULL). But what if I want to return null values for certain use cases which I am driving based on input from consumers?

I have a search API being consumed by multiple consumers. Below are the scenarios I want my API to be able to handle using the same response object.

Scenario Expected Request Expected Response
Null Values are expected in response { "nullsInResponse": true } { "attribute1": "value1", "attribute2": null }
Null Values are not expected in response { "nullsInResponse": false } { "attribute1": "value1" }
  • Are you asking about different behaviors for different fields of the same class, or about different behaviors for different places of use of the class? – M. Dudek Nov 29 '21 at 13:32
  • @M. Dudek I updated the problem statement. Hope it clarifies – MittulRazdan Nov 29 '21 at 13:41
  • You would need to write own implementation of `com.fasterxml.jackson.databind.JsonSerializer` that will either write or omit field based on other POJO's field value. See [example](https://www.baeldung.com/jackson-custom-serialization#on-mapper) – Nick Nov 29 '21 at 15:19
  • As per the example, we need to provide attribute names and their data type in custom implementation. In case attributes are added or removed, this serializer would also needs updates creating unnecessary efforts. This solution does not seem scalable. Is there any solution possible using mapstruct? – MittulRazdan Nov 29 '21 at 17:21

2 Answers2

0

on class level you can do @JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)

on attribute level @XmlElement(nillable = true) @JsonProperty("error") private Error error;

Deb Das
  • 264
  • 1
  • 7
0

In my opinion, the best option for your case is creating 2 different DTOs for response with null values and without them, based on @JsonSerialize annotation.

It's reasonable, because you have two different business cases, so you can provide different transfer objects with names based on that cases (ResponseWithNullValues and Response for example).

Of course, you can always use reflection to add annotation dynamically, but... we should avoid reflection whenever possible. Your business logic doesn't see anything about building specific rules for every field, so for me it's clear place to use two separated DTOs.

M. Dudek
  • 978
  • 7
  • 28