我想忽略多少属性(我从UI获得),如
filtervalue0,filtervalue1,filtervalue2等
然而,我从UI
获得此计数即。 if filterscount = 3 我知道,会有 filtervalue0,filtervalue1,filtervalue2
是否可以动态地进行此工作(即@JsonIgnoreProperties)
答案 0 :(得分:3)
您可以使用@JsonFilter
动态过滤字段Serialization
或Deserialization
。
例如:
@JsonFilter("myFilter")
static class Bean {
public String filtervalue0 = "a";
public String filtervalue1 = "b";
public int filtercount = 1;
public int totalFilters = 2;
}
static void test() throws JsonProcessingException{
Bean value = new Bean();
ObjectMapper mapper = new ObjectMapper();
Set<String> filtersToExclude = new HashSet<>();
//logic for applying filter
for(int i=value.totalFilters-1; i>value.totalFilters-value.filtercount-1; i--){
filtersToExclude.add("filtervalue"+i);
}
//dynamic field filtering is provided by FilterProvider
FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter",
SimpleBeanPropertyFilter.filterOutAllExcept(filtersToExclude));
String json = mapper.setFilterProvider(filters).writeValueAsString(value);
System.out.println(json); // prints {"filtervalue1":"b"}
}
public static void main(String[] args) throws JsonProcessingException {
test();
}