Если вы используете Jackson 2.6 или выше, вы можете использовать FilteringParserDelegate
с пользовательским TokenFilter
.
public class PropertyBasedIgnoreFilter extends TokenFilter {
protected Set<String> ignoreProperties;
public PropertyBasedIgnoreFilter(String... properties) {
ignoreProperties = new HashSet<>(Arrays.asList(properties));
}
@Override
public TokenFilter includeProperty(String name) {
if (ignoreProperties.contains(name)) {
return null;
}
return INCLUDE_ALL;
}
}
При создании FilteringParserDelegate
с этим PropertyBasedIgnoreFilter
убедитесь, что оба логических значения includePath
и allowMultipleMatches
равны true
.
public class Main {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonInput = "{\"_p1\":1,\"_p2\":2,\"_id\":\"id\",\"_p3\":{\"_p3.1\":3.1,\"_id\":\"id\"}}";
JsonParser filteredParser = new FilteringParserDelegate(mapper.getFactory().createParser(new ByteArrayInputStream(jsonInput.getBytes())),
new PropertyBasedIgnoreFilter("_id"),
true,
true);
JsonNode tree = mapper.readTree(filteredParser);
System.out.println(jsonInput);
System.out.println(tree);
System.out.println(jsonInput.equals(tree.toString()));
}
}
печать
{"_p1":1,"_p2":2,"_id":"id","_p3":{"_p3.1":3.1,"_id":"id"}}
{"_p1":1,"_p2":2,"_p3":{"_p3.1":3.1,"_id":"id"}}
false
Как видите, вложенные вхождения _id
не отфильтровываются. В случае, если это не то, что вам нужно, вы, конечно, можете расширить мою PropertyBasedIgnoreFilter
своей собственной реализацией TokenFilter
.