public class TreeNodeUtils {
private static JsonNode result = JsonUtils.objectMapper().nullNode();
public static JsonNode fetch(JsonNode node, Predicate<JsonNode> predicate) {
if (!node.isObject()) {
node = mock(node);
JsonNode test = test(node, predicate);
return test.get("children");
}
return test(node, predicate);
}
private static JsonNode mock(JsonNode node) {
String mockStr = "{\"id\": \"idTest\", \"name\" : \"nameTest\"}";
JsonNode mockNode = JsonUtils.toJson(mockStr);
JsonUtils.writeJsonNode(mockNode, "children", node);
return mockNode;
}
private static JsonNode test(JsonNode node, Predicate<JsonNode> predicate) {
AtomicReference<JsonNode> rsJson = new AtomicReference<>(JsonUtils.objectMapper().nullNode());
if (predicate.test(node)) {
return appendNode(result, node);
}
JsonNode children = node.get("children");
if (children.isArray()) {
children.iterator().forEachRemaining(child -> {
JsonNode found = test(child, predicate);
if (found.isObject()) {
rsJson.set(appendNode(result, node));
JsonUtils.writeJsonNode(rsJson.get(), "children", JsonUtils.arrayNode().add(found));
result = rsJson.get();
}
});
}
return rsJson.get();
}
private static JsonNode appendNode(JsonNode result, JsonNode node) {
if (result.isNull()) {
return node.deepCopy();
}
JsonNode copyNode = JsonUtils.copyOf(node);
Iterator<JsonNode> iterator = copyNode.iterator();
while (iterator.hasNext()) {
if (iterator.next().isArray()) {
iterator.remove();
}
}
return copyNode;
}
}
Java 查找树的某子支 并组装Json
最新推荐文章于 2024-04-30 11:32:30 发布