配置Jackson以忽略除课程字段/成员之外的所有内容

问题描述

我有一个Spring Boot 2.3.2.RELEASE WebFlux应用程序。我有一些JPA实体是作为RESTful API响应的一部分返回的。

问题在于,当我向这些JPA实体添加方法(公开行为)时,这些返回类型/值也被发送回,我想避免这种情况。

基本上,我要寻找的是配置Jackson的方式,以便仅(反)序列化类字段/成员以及所有带有@JsonProperty注释的内容。我还可以采用以下方法认情况下忽略所有内容,并将@JsonProperty放在我要反序列化的成员上。

另请注意:

  • 那些类没有设置器,通常没有构造函数(除了必需的无参数一个)。他们大多数时候都使用建筑商。

  • 我知道我可以用@JsonIgnore注释那些方法,但是会有很多,所以我想知道是否还有另一种解决方案仅包含(类的)字段/成员以及带有@JsonProperty注释的任何内容

解决方法

是否可用取决于您的实际代码,但是您可以查看可见性。您可以像这样配置ObjectMapper

om.setVisibility(PropertyAccessor.FIELD,JsonAutoDetect.Visibility.ANY);
om.setVisibility(PropertyAccessor.GETTER,JsonAutoDetect.Visibility.NONE);

然后按照注释中的说明完成类似以下序列化的类:

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 :)";
    }

}