In some of the previous posts we have seen the conversions of JSON to and from Java objects.
Java to JSON & JSON to Java.
While converting Java class into JSON, we may sometimes have some null values that we do not want to get converted into JSON. We can Ignore Null fields in JSON using Jackson to get converted.
There are many ways in which we can achieve this.
Lets go from the field level to global level
1. Field Level Ignore Null Value
You can choose individual fields that you think may result in a NULL value and you want to ignore them.
Example: I wanted to not include any NULL values from department
1 2 3 4 5 6 7 8 9 10 11 |
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; public class Employee { private int empId; private String name; @JsonInclude(Include.NON_NULL) private String department; |
2. Class Level Ignore Null Value
If you do not want to choose which NULL value you do not want, and rather let the Object decide then you can use the same annotation on the Class level
1 2 3 4 5 6 7 8 9 10 11 |
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(Include.NON_NULL) public class Employee { private int empId; private String name; private String department; |
3. Object Mapper level Ignore Null Value
If you want to have a global configuration that Ignores any NULL value from getting serialized, then you can use the Object Mapper level Ignore.
1 2 |
ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_EMPTY); |
Note: In similar way we can include Empty values from getting serialized. You need to use Include.NON_EMPTY instead.