Jackson忽略类的属性字段

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")));
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值