1.概述
使用Jackson 2.x将对象序列化为JSON时如何忽略某些字段。
当Jackson的默认值还不够,并且需要精确控制要序列化为JSON的内容时,有几种方法可以忽略属性。
2.忽略类级别的字段
可以使用@JsonIgnoreProperties批注并按名称指定字段,从而在类级别忽略特定字段:
@Data
@NoArgsConstructor
@JsonIgnoreProperties(value = {
"intValue" })
public class MyFieldsDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
}
@Test
public void test18() throws IOException {
ObjectMapper mapper = new ObjectMapper();
MyFieldsDto myFieldsDto = new MyFieldsDto();
String dtoAsString = mapper.writeValueAsString(myFieldsDto);
System.out.println(dtoAsString);//{"stringValue":null,"booleanValue":false}
}
3.在字段级别忽略字段
@Data
@NoArgsConstructor
public class MyFieldsDto {
private String stringValue;
private int intValue;
@JsonIgnore
private boolean booleanValue;
}
@Test
public void test19() throws IOException {
ObjectMapper mapper = new ObjectMapper();
MyFieldsDto myFieldsDto = new MyFieldsDto();
String dtoAsString = mapper.writeValueAsString(myFieldsDto);
System.out.println(dtoAsString);//{"stringValue":null,"intValue":0}
}
4.按类型忽略所有字段
最后,可以使用@JsonIgnoreType忽略指定类型的所有字段:
@JsonIgnoreType
public class SomeType {
... }
但是,很多时候,无法控制类本身。 在这种情况下,可以充分利用Jackson的mixins。
首先,要为忽略的类型定义一个MixIn,并使用@JsonIgnoreType对其进行注释:
@JsonIgnoreType
public class MyMixInForIgnoreType {
}
@Data
@NoArgsConstructor
public class MyDtoWithSpecialField {
private String[] stringValue;
private Integer intValue;
private Boolean booleanValue;
}
然后,在编码期间注册该mixin来替换(并忽略)所有String []类型:
@Test
public void test21() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
dtoObject.setBooleanValue(true);
String dtoAsString = mapper.writeValueAsString(dtoObject);
System.out.println(dtoAsString);//{"intValue":null,"booleanValue":true}
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}