Jackson How to ignore null fields
By:Roy.LiuLast updated:2019-08-11
In Jackson, we can use @JsonInclude(JsonInclude.Include.NON_NULL) to ignore the null fields.
P.S Tested with Jackson 2.9.8
1. Jackson default include null fields
1.1 Reviews a POJO, for testing later.
Staff.java
public class Staff {
private String name;
private int age;
private String[] position;
private List<String> skills;
private Map<String, BigDecimal> salary;
1.2 By default, Jackson will include the null fields.
JacksonExample.java
package com.mkyong;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Staff staff = new Staff("mkyong", 38);
try {
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
Output
"name" : "mkyong", "age" : 38, "position" : null, "skills" : null, "salary" : null
To ignore the null fields, put @JsonInclude on class level or field level.
2. @JsonInclude – Class Level
Staff.java
import com.fasterxml.jackson.annotation.JsonInclude;
// ignore null fields , class level
@JsonInclude(JsonInclude.Include.NON_NULL) // ignore all null fields
public class Staff {
private String name;
private int age;
private String[] position;
private List<String> skills;
private Map<String, BigDecimal> salary;
//...
Output
"name" : "mkyong", "age" : 38
3. @JsonInclude – Field Level
Staff.java
import com.fasterxml.jackson.annotation.JsonInclude;
public class Staff {
private String name;
private int age;
@JsonInclude(JsonInclude.Include.NON_NULL) //ignore null field on this property only
private String[] position;
@JsonInclude(JsonInclude.Include.NON_NULL) //ignore null field on this property only
private List<String> skills;
private Map<String, BigDecimal> salary;
Output
"name" : "mkyong", "age" : 38, "salary" : null
4. ObjectMapper.setSerializationInclusion
Alternatively, we also can configure to ignore null fields globally:
JacksonExample2.java
package com.mkyong;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JacksonExample2 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Staff staff = new Staff("mkyong", 38);
try {
// ignore the null fields globally
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
Output
"name" : "mkyong", "age" : 38
From:一号门
Previous:Jackson How to parse JSON

COMMENTS