JSON using Jackson in REST API Implementation with Spring Boot
Whenever we are implementing a REST API with Spring (Spring Boot) , we would have come across the requirement to exclude NULLs in the JSON Response of the API. Also, there might be a requirement to externalize turning ON/OFF this feature: Exclude NULLS in the JSON Response , thereby allowing the consumer of the API to customize as per the need.
In this article, we summarize the approach that used to implement the Externalization of ON/OFF the above-mentioned feature using Jackson – A java-based library to serialize or map java objects to JSON and vice versa.
Unsuccessful Approaches :
Initially, we 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.
Java
@Configuration
class WebMvcConfiguration extends WebMvcConfiguration{
@Override
protected void extendsMessageConverters
(List<HttpMessageConverter<?>> converters)
{
for(HttpMessageConverter<?> converter: converters)
{
if(converter instnceof MappingJackson2HttpMessageConverter)
{
ObjectMapper mapper =
((MappingJackson2HttpMessageConverter)converter)
.getObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
}
}
}
Now, Creating an instance of org.springframework.http.converter.json.Jackson2ObjectMapperBuilderCustomizer , Below the given code is for your reference.
Java
@Bean
Public Jackson2ObjectMapperBuilderCustomizer customJackson(){
return new Jackson2ObjectMapperBuilderCustomizer(){
@Override
public void customize(Jackson2ObjectMapperBuilder builder){
builder.serializationInclusion(Include.NON_NULL);
builder.failonUnknownProperties(false);
}
};
}
Successful Approach:
Create a JSON Response Object, if not created. This is the object which while serializing to JSON you want to ‘Exclude/Include Null fields ’ feature based on the property in application.properties . You can see below the Response object for your reference.
Java
public class RegistrationResponse{
@JsonProperty("success")
private Boolean success = null;
@JsonProperty("message")
private String message = null;
@JsonProperty("data")
private String data = null;
@JsonProperty("error_code")
private Integer errorCode = null;
public RegistrationResponse success(Boolean success){
this.success = success;
return this;
}
@NotNull
public Boolean isSuccess(){
return success;
}
public void setSuccess(Boolean success){
this.success = success;
}
public RegistrationResponse message(String message){
this.message = message;
return this;
}
@NotNull
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message = message;
}
Create a property by the name ‘config.response.json.format.exclude_null ’ which can take values as ‘true ’ or ‘false ’. The value ‘true ’ means to exclude null fields in the JSON Response & the value ‘false ’ means to not exclude null fields. Also, bind this property to a class-level property so that the value can be read, Below given code is for your reference.
config.response.json.format.exclude_null = false
@Value("${config.response.json.format.exclude_null}")
private boolean toExcludeNull;
Implement the actual logic to exclude nulls based on the global 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 true, otherwise set to Include.ALWAYS .
Serialize the Response object to a String using the mapper & return the String. Make sure to handle JsonProcessingException .
Let’s see below for the actual code snippet to be added while constructing the JSON Response as part of the API implementation.
Java
RegistrationResponse regResp = new RegistrationResponse();
regResp.setSuccess(true);
regResp.setErrorCode(null);
regResp.setData("testdata");
regResp.setMessage("success");
ObjectMapper mapper = new ObjectMapper()
mapper.enable(SerializationFeature.INDENT_OUTPUT);
if(toExcludeNull) mapper.setSerializationInclusion(Include.NON_NULL);
else mapper.serializationInclusion(Include.ALWAYS);
String regRespStr = null;
try{
regRespStr = mapper.writeValueAsString(regResp);
}
catch(JsonProcessingException e)
e.printStackTrace();
}
System.out.println("Formatted JSON Response:" + regRespStr);
Here, regRespStr is the JSON String with NULL exclusion/inclusion applied.
You can also check the Github Repository .
Last Updated :
27 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...