'is' 不是@JsonIgnore-d
'is' not @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}
一个解决方案是将 @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;
}
对于 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}
一个解决方案是将 @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;
}