一、忽略某一个值为 Null 的属性
import com.fasterxml.jackson.annotation.JsonInclude;
public class Person {
private String name;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
二、忽略 Class 下的所有值为 Null 的属性
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
三、全局配置,忽略所有待序列化对象的 Null 属性
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTest {
private final static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static void main(String[] args) throws JsonProcessingException {
Person person = new Person();
person.setName("iyushu");
System.out.println(objectMapper.writeValueAsString(person));
}
}