首页 > 解决方案 > '不是'@JsonIgnore-d

问题描述

使用 Lombok 1.18.12 和 Jackson 2.11.0,这个 POJO:

@Data @NoArgsConstructor
private static class MyPojo {
    private Long id = 1L;
    private boolean isGood = true;
    @JsonIgnore
    private boolean isIgnored = false;

}

不忽略该isIgnored字段,因此测试失败:

@Test
public void serializePojo() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    MyPojo pojo = new MyPojo();
    String actualJson = objectMapper.writeValueAsString(pojo);
    String expectedJson = "{\"id\":1,\"good\":true}";

    assertThat(actualJson).asString().isEqualToIgnoringWhitespace(expectedJson);
}

因为实际的 JSON 是:

JSON{"id":1,"ignored":false,"good":true}

标签: javaserializationjacksonlombok

解决方案


一种解决方案是添加@JsonIgnore到显式 getter:

@Data @NoArgsConstructor
private static class MyPojo {
    private Long id = 1L;
    private boolean isGood = true;
    private boolean isIgnored = true;

    @JsonIgnore
    public boolean isIgnored() {
        return isIgnored;
    }

}

一种解决方法是避免is布尔属性上的(通用)前缀:

@Data @NoArgsConstructor
private static class MyPojo {
    private Long id = 1L;
    private boolean isGood = true;
    @JsonIgnore
    private boolean ignored = true;

}

推荐阅读