Enable/Disable Null Fields in a JSON Response
How to use JSON Include.NON_NULL flag in Spring Boot as an External Property — find out more in the article!
Join the DZone community and get the full member experience.
Join For FreeProblem
We need to have a SWITCH to enable or disable the inclusion of NULL fields in the API Response in the form of property:
Solution
- In this example, ‘RegistationResponse’ is the response object for our API. This is the object in which we want to use the ‘Enable/Disable Null fields’ flag so that the response contains NULL fields or not based on the property ‘config.response.format.include.null’ present in the application.properties file:
- Declare the property ‘config.response.format.include.null’ in application.properties file:
- Bind this property to a class-level property so that the value can be read:
- Implement the actual logic to include nulls based on the property value by:
- Creating an instance of com.fasterxml.jackson.databind.ObjectMapper.
- Setting SerializationInclusion property of the created mapper to Include.NON_NULL if the global property value is false, otherwise set to Include.ALWAYS.
- Serializing the Response object to a String using the mapper & return the String. Make sure to handle JsonProcessingException.
See below for the actual code snippet to be added while constructing the JSON Response as part of the API implementation:
Where regRespStr is the JSON String with NULL exclusion/inclusion applied.
Source code is available in GitHub @ this location.
Common Mistakes
Initially, I tried with the Spring Boot’s readily available approaches, which were not successful, such as:
- Having spring.jackson.default-property-inclusion property in application.properties. This property takes values such as: always/non_null/non_absent/non_default/non_empty.
- Extending WebMvcConfigurationSupport class and customize the Spring Boot configuration, see below:
- Creating an instance of org.springframework.http.converter.json.Jackson2ObjectMapperBuilderCustomizer, see below:
Conclusion
The decision of whether to include the NULL fields in a JSON can be externalized using Spring Boot.
Source code is available in GitHub @ this location.
Opinions expressed by DZone contributors are their own.
Comments