1.概述
如何在序列化Java类时将Jackson设置为忽略空字段。
2.忽略类中的空字段
jackjson允许在任何一个类上控制这种行为:
@JsonInclude(Include.NON_NULL)
public class MyDto { ... }
或更详细地在字段级别:
@Data
public class MyDtoField {
@JsonInclude(JsonInclude.Include.NON_NULL)
private String stringValue;
private int intValue;
}
@Test
public void test22() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
MyDtoField dtoObject = new MyDtoField();
String dtoAsString = mapper.writeValueAsString(dtoObject);
System.out.println(dtoAsString);//{"intValue":0}
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}
3.全局忽略空字段
Jackson还允许我们在ObjectMapper上全局配置此行为:
mapper.setSerializationInclusion(Include.NON_NULL);
@Data
public class MyDtoGlobalField {
private String stringValue;
private int intValue;
private boolean booleanValue;
}
@Test
public void test23() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MyDtoGlobalField dtoObject = new MyDtoGlobalField();
String dtoAsString = mapper.writeValueAsString(dtoObject);
System.out.println(dtoAsString);//{"intValue":0,"booleanValue":false}
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}