【问题标题】:Configure Jackson to ignore everything but class fields/members将 Jackson 配置为忽略除类字段/成员之外的所有内容
【发布时间】:2021-01-15 13:15:04
【问题描述】:
我有一个 Spring Boot 2.3.2.RELEASE WebFlux 应用程序。我有一些 JPA 实体作为 RESTful API 响应的一部分返回。
问题在于,当我向这些 JPA 实体添加方法(暴露行为)时,这些返回类型/值也会被发回,我想避免这种情况。
基本上,我正在寻找的是配置 Jackson 以仅(反)序列化类字段/成员以及任何带有 @JsonProperty 注释的内容。我也可以采用默认忽略所有内容的方法,并将@JsonProperty 放在我想要(反)序列化的成员上。
另请注意:
【问题讨论】:
标签:
java
json
spring-boot
jackson
jackson2
【解决方案1】:
可能性取决于您拥有的实际代码,但您可以查看可见性。您可以像这样配置ObjectMapper:
om.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
om.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
然后像下面这样的类将按照 cmets 中的说明进行序列化:
public static class TestClass {
@Getter // getter is generated but ignored
// because visibility for GETTER is NONE
// still serialized because visibility for FIELD is ANY
private String fieldThatShouldBeSerialized = "It is OK to serialize me :)";
// not serialized because visibility for GETTER is NONE
public String getMethodThatShouldNotBeSerialized() {
return "It is NOT OK to serialize me :(";
}
@JsonProperty // serialized because explicitly asked (not auto)
public String methodThatShouldBeSerialized() {
return "It is OK to serialize me also :)";
}
@JsonProperty // serialized because explicitly asked (not auto)
// even it is a "getter"
public String getAnotherMethodThatShouldBeSerialized() {
return "It is OK to serialize me also :)";
}
}