忽略给定的自定义值 Jackson JSON

whi*_*fin 3 java json jackson

如果我有一个值设置为“custom_string”的属性,在使用 POJO 和 Jackson 时有没有办法忽略它?

我知道您可以使用 忽略 null @JsonInclude(Include.NON_NULL),但是有没有办法忽略自定义值?我似乎无法在任何地方找到任何关于此的注释。

我知道有可能只return value.equals("custom_string") ? null : value在我的 Getter 中......但我更喜欢更优雅的方式。

vga*_*uza 6

另一种可能的解决方案是使用自定义过滤器,您可以在其中组合多个需求。假设我们要过滤空值和“custom_string”,那么我们应该指定我们将使用 JsonInclude.Include.CUSTOM 值并提供过滤器实现。例子:

@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = StringFilter.class)
private String name;

// Custom filter that will omit null and "custom_string" values.
public class StringFilter {
    @Override
    public boolean equals(Object other) {
        if (other == null) {
            // Filter null's.
            return true;
        }

        // Filter "custom_string".
        return "custom_string".equals(other);
    }
}
Run Code Online (Sandbox Code Playgroud)