gpt4 book ai didi

java - 忽略所有属性但列出的属性的 Jackson 字段注释

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:20:11 26 4
gpt4 key购买 nike

是否有针对字段和/或 getter 的 Jackson 注释忽略字段值的所有属性(列出的属性除外)?

当应用于字段时,它类似于 @JsonIgnoreProperties,不同之处在于它不包括除列出的属性之外的所有属性,而是排除除列出的属性之外的所有属性。

例如,如果注释被命名为 @JsonIncludeProperties:

class A {
final int a = 1;
final int b = 1;
... // final int c = 1; through final int y = 1;
final int z = 1;
}

class B {
@JsonProperty
@JsonIncludeProperties({"m", "o"})
A a1;
@JsonProperty
A a2;
}

将序列化为:

{
"a1": {
"m": 1,
"o": 1
},
"a2": {
"a": 1,
"b": 1,
... // "c": 1, through "y": 1,
"z": 1
}
}

最佳答案

你可以使用the Jackson filters来实现和自定义注释。这是一个例子:

public class JacksonIncludeProperties {
@Retention(RetentionPolicy.RUNTIME)
@interface JsonIncludeProperties {
String[] value();
}

@JsonFilter("filter")
@JsonIncludeProperties({"a", "b1"})
static class Bean {
@JsonProperty
public final String a = "a";
@JsonProperty("b1")
public final String b = "b";
@JsonProperty
public final String c = "c";
}

private static class IncludePropertiesFilter extends SimpleBeanPropertyFilter {

@Override
protected boolean include(final PropertyWriter writer) {
final JsonIncludeProperties includeProperties =
writer.getContextAnnotation(JsonIncludeProperties.class);
if (includeProperties != null) {
return Arrays.asList(includeProperties.value()).contains(writer.getName());
}
return super.include(writer);
}
}

public static void main(String[] args) throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
final SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("filter", new IncludePropertiesFilter());
objectMapper.setFilters(filterProvider);
System.out.println(objectMapper.writeValueAsString(new Bean()));
}
}

关于java - 忽略所有属性但列出的属性的 Jackson 字段注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com