英文:
'is' not @JsonIgnore-d
问题
With Lombok 1.18.12 and Jackson 2.11.0, this POJO:
@Data @NoArgsConstructor
private static class MyPojo {
private Long id = 1L;
private boolean isGood = true;
@JsonIgnore
private boolean isIgnored = false;
}
does not ignore the isIgnored
field so the test fails:
@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);
}
because the actual JSON is:
JSON{"id":1,"ignored":false,"good":true}
英文:
With Lombok 1.18.12 and Jackson 2.11.0, this POJO:
@Data @NoArgsConstructor
private static class MyPojo {
private Long id = 1L;
private boolean isGood = true;
@JsonIgnore
private boolean isIgnored = false;
}
does not ignore the isIgnored
field so the test fails:
@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);
}
because the actual JSON is:
JSON{"id":1,"ignored":false,"good":true}
答案1
得分: 0
Sure, here are the translated parts:
一种解决方法是将 @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;
}
英文:
One solution is to add @JsonIgnore
to an explicit 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;
}
}
A work-around is to avoid the (common) is
prefix on boolean properties:
@Data @NoArgsConstructor
private static class MyPojo {
private Long id = 1L;
private boolean isGood = true;
@JsonIgnore
private boolean ignored = true;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论