There is a feature of Jackson ObjectMapper which allows empty values to be removed:
class Car { Optional<String> ownerName; String manufacturer; public Optional<String> getOwnerName() { return ownerName; } public String getManufacturer() { return manufacturer; } } Car batMobile = new Car(); batMobile.owner = Optional.of("Batman"); batMobile.manufacturer = null; Car stolenCar = new Car(); stolenCar.owner = Optional.empty(); stolenCar.manufacturer = "Tesla"; ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_ABSENT); mapper.writeValueAsString(batMobile); /* { "ownerName": "Batman" } */ mapper.writeValueAsString(stolenCar); /* { "manufacturer": "Tesla" } */ What I want instead is for Optional.empty values to be removed, but null values to remain:
mapper.writeValueAsString(batMobile); /* { "ownerName": "Batman", "manufacturer": null } */ mapper.writeValueAsString(stolenCar); /* { "manufacturer": "Tesla" } */ And I want this to apply globally without needing any annotations on the DTOs.