如何保持所有嵌套对象具有相同的属性名称? 例如。顶级课程是政策。
@JsonFilter("myFilter")
public class Policy {
String name;
String number;
List<Participant> participants;
List<Asset> assets;
Map<String, String> additionalFields;
}
@JsonFilter("myFilter")
public class Participant {
String name;
String number;
List<Asset> assets;
Map<String, String> additionalFields;
}
@JsonFilter("myFilter")
public class Asset {
String name;
String number;
Map<String, String> additionalFields;
}
现在,我想排除响应中所有对象上除 extraFields 之外的所有字段。我有以下实现,但这会删除所有内容,只保留策略上的附加字段。
SimpleFilterProvider filterProvider = new SimpleFilterProvider() .addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("additionalFields"));
你描述的情况,如果不包括其他依赖,它实际上是2个过滤器来实现你的目标(因为你的使用行为是从上到下的过滤器,并用属性名称来判断)。例如
@JsonFilter("policyFilter")
public class Policy {
String name;
String number;
List<Participant> participants;
List<Asset> assets;
Map<String, String> additionalFields;
}
@JsonFilter("myFilter")
public class Participant {
String name;
String number;
List<Asset> assets;
Map<String, String> additionalFields;
}
@JsonFilter("myFilter")
public class Asset {
String name;
String number;
Map<String, String> additionalFields;
}
PropertyFilter policyFilter= SimpleBeanPropertyFilter.filterOutAllExcept("additionalFields","participants","assets");
PropertyFilter myFilter = SimpleBeanPropertyFilter.filterOutAllExcept("additionalFields");
SimpleFilterProvider filterProvider = new SimpleFilterProvider() .addFilter("myFilter", myFilter );
如果你想使用一个过滤器来控制序列化,jackson标准过滤器不支持这样的嵌套属性,https://github.com/FasterXML/jackson-databind/issues/1040中有一些讨论。 但存在一些社区解决方案。你可以使用它们
https://github.com/krishna81m/jackson-nested-prop-filter
如果您使用上面的解决方案,代码应该是
@JsonFilter("myFilter")
public class Policy {
String name;
String number;
List<Participant> participants;
List<Asset> assets;
Map<String, String> additionalFields;
}
// @JsonFilter("myFilter")
public class Participant {
String name;
String number;
List<Asset> assets;
Map<String, String> additionalFields;
}
// @JsonFilter("myFilter") there is no need to specific such config,access graph already in NestedPropertyFilterProvider
public class Asset {
String name;
String number;
Map<String, String> additionalFields;
}
FilterProvider filterProvider = new NestedPropertyFilterProvider()
.addFilter("myFilter",
NestedBeanPropertyFilter.filterOutAllExcept(Policy.class,
"additionalFields",
"participants.additionalFields", // nest property
"assets.additionalFields")); // nest property