I was asked in an interview that you have an API - say getCustomer. This API returns details of the customer. But to reduce the size of the REST response, we need to return only the attributes which have value. So if middleName is not there for the customer, we should not see { middleName=null } in the response. How can we do this?
            Asked
            
        
        
            Active
            
        
            Viewed 313 times
        
    2
            
            
         
    
    
        Ihor Patsian
        
- 1,288
- 2
- 15
- 25
 
    
    
        user3276247
        
- 1,046
- 2
- 9
- 24
2 Answers
1
            
            
        Using Jackson you can exclude null values from JSON serialization in two ways:
- Globally (for all classes) by setting the property JsonInclude.Include.NON_NULL in the ObjectMapper, as already suggested by ritesh.garg - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
- At single class level, annotating the class with @JsonInclude(Include.NON_NULL) as follows: - @JsonInclude(Include.NON_NULL) public class Customer { }
Here you can find a detailed explanation and code samples: Jackson: how to exclude null value properties from JSON serialization
 
    
    
        Davis Molinari
        
- 741
- 1
- 5
- 20
0
            
            
        You can configure it with your message converter configuration. E.g. in case one is using Jackson Message Converter it can be set using the serialization inclusion property of Jackson Object mapper.
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
 
    
    
        ritesh.garg
        
- 3,725
- 1
- 15
- 14