Allow to suppress null values in serialization
Ironlink opened this issue · 1 comments
In order to minimize my response body size from my REST controllers, I would like to be able to supress all null values when serializing to JSON, however when I changed my ObjectMapper
to use Include.NON_NULL
by default I found that suppressNull
is hard coded to false
in JsonNullableSerializer
. This results in considerable bloat.
You might wonder why I don't use JsonNullable.undefined()
instead. I have an OpenAPI schema with 679 different fields, of which 174 are nullable. Keeping track of which fields are nullable, and changing all of those converter classes to use JsonNullable
is quite a lot of work. On top of that, the Java models generated with openapi-generator-maven-plugin
do not create fluent setters for JsonNullable
.
It would save me a lot of effort if JsonNullableSerializer
would just respect suppressNull
, is that something you would agree to change?
If not, I could submit a PR to add a setting to JsonNullableModule
to toggle whether suppressNull
should be respected?
To give a concrete example, imagine I have a business model such as:
public record Person(String firstName, String lastName, String bio, String title, Country country) {}
I would then map that to my api model such as:
public static PersonApiModel fromBusinessModel(Person person) {
return new PersonApiModel()
.firstName(person.firstName())
.lastName(person.lastName())
.bio(person.bio())
.title(person.title())
.country(person.country());
}
If I for instance allow nulls for bio, title, and country, this would result in the Api model setter being called with explicit null. Which in turn would become a JsonNullable.of(null)
, and be serialized with literal nulls.
Like @Ironlink said, I have a bunch of these properties, and we would ideally not want to rewrite all of our business->api conversions with the following pattern:
var apiModel = new PersonApiModel()
.firstName(person.firstName())
.lastName(person.lastName());
if (person.bio() != null) {
apiModel.bio(person.bio());
}
if (person.title() != null) {
apiModel.title(person.title());
}
... etc for every possible field that can be null in java.