Removing null values from JSON responses in Spring Boot

Sitewide-10usd300x250 We often return partially filled objects from our controller methods.

For example, when returning the current user data, you’d not like the password and other sensitive fields to be returned. You may create a new user object, only fill the fields that you’d like returned, and then return that object.

Then, if you look at the response, it’ll have all the fields, including the ones that you didn’t fill. The unfilled fields will have null values, though. See this response for example:

   "id": 5,
   "name": "Sanjay Patel",
   "password: null,
   "birthDate": null,
   "email": null

Wouldn’t it instead be nicer to remove all the null valued items? In other words, have just

   "id": 5,
   "name": "Sanjay Patel"

Do you know that, if you are using Spring Boot, this can be achieved just by adding a single line in your application properties:

spring.jackson.default-property-inclusion: NON_NULL

Happy coding!

2 thoughts on “Removing null values from JSON responses in Spring Boot

Leave a Reply

Your email address will not be published. Required fields are marked *