首页 > 解决方案 > 将 Jackson 配置为忽略除类字段/成员之外的所有内容

问题描述

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

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

基本上,我正在寻找的是配置 Jackson 以仅(反)序列化类字段/成员和任何用@JsonProperty. 我也可以采用默认忽略所有内容的方法,并将其@JsonProperty放在我想要(反)序列化的成员上。

另请注意:

标签: javajsonspring-bootjacksonjackson2

解决方案


可能性取决于您拥有的实际代码,但您可以检查visibility。你可以配置你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 :)";
    }

}

推荐阅读