I'm trying to return only the properties that have values, but the null ones are also being returned.
I know that there's an annotation that does this ( @JsonInclude(Include.NON_NULL)
), but then I need these in every single entity class.
So, my question is: Is there a way to configure this globally through spring config? (avoiding XML, preferably)
EDIT: It seems that this question has been considered a duplicate, but I don't think so. The real question here is how to configure it through spring config, which I couldn't find in other questions.
In newer versions of Spring Boot (2.0+), use:
If you are using Spring Boot, this is as easy as:
If not, then you can configure the ObjectMapper in the MappingJackson2HttpMessageConverter like so:
The programmatic alternative to Abolfazl Hashemi's answer is the following:
This way, you're basically telling to the Spring container that, every time an
ObjectMapper
is used, only properties with non-null values are to be included in the mappings.If you use jackson ObjectMapper for generating json, you can define following custom ObjectMapper for this purpose and use it instead: