‘is’ 不是 @JsonIgnore 的

huangapple go评论72阅读模式
英文:

'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;

}

huangapple
  • 本文由 发表于 2020年7月31日 21:47:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63193077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定