java - '不是'@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;
}
推荐阅读
- mongodb - MongoDB .- 为数组的每个元素创建一个字段
- vue.js - 如何使用 vue-plotly 模块覆盖 Plotly.js 方法(downloadImage)
- c - 用 ; 循环 在 C 中
- python - 在 Python Django 中正确链接到 index.html
- java - PDFBox IOException:错误:文件结束,预期行
- xamarin - Xamarin Forms 5 - Android.Content.PM.Permission[] grantResults
- azure - 以编程方式将 Azure CSP 订阅分配给您的客户
- java - 通过 Hibernate 在 db 上保存时不存在实体错误
- android - 需要 Kotlin 适配器:Int 找到:字符串?
- hibernate - 如何配置 Grails 2.5.1 以使用 Hibernate 5?