一、 忽略某一个值为 Null 的属性
import com.fasterxml.jackson.annotation.JsonInclude;publicclassPerson{private String name;@JsonInclude(JsonInclude.Include.NON_NULL)private Integer age;public StringgetName(){return name;}publicvoidsetName(String name){this.name= name;}public IntegergetAge(){return age;}publicvoidsetAge(Integer age){this.age= age;}}
二、忽略 Class 下的所有值为 Null 的属性
import com.fasterxml.jackson.annotation.JsonInclude;@JsonInclude(JsonInclude.Include.NON_NULL)publicclassPerson{private String name;private Integer age;public StringgetName(){return name;}publicvoidsetName(String name){this.name= name;}public IntegergetAge(){return age;}publicvoidsetAge(Integer age){this.age= age;}}
三、全局配置,忽略所有待序列化对象的 Null 属性,
import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;publicclassJacksonTest{privatefinalstatic ObjectMapper objectMapper=newObjectMapper();static{
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);}publicstaticvoidmain(String[] args)throws JsonProcessingException{
Person person=newPerson();
person.setName("iyushu");
System.out.println(objectMapper.writeValueAsString(person));}}