2020-03-20 17:20:22 +01:00
|
|
|
package eu.eudat.logic.utilities.json;
|
|
|
|
|
|
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
2020-03-23 17:09:31 +01:00
|
|
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
2020-03-20 17:20:22 +01:00
|
|
|
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.Iterator;
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
public class JsonSearcher {
|
|
|
|
|
|
|
|
public static List<JsonNode> findNodes(JsonNode root, String key, String value) {
|
2020-06-12 16:25:53 +02:00
|
|
|
return findNodes(root, key, value, false);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static List<JsonNode> findNodes(JsonNode root, String key, String value, boolean parent) {
|
2020-03-20 17:20:22 +01:00
|
|
|
List<JsonNode> nodes = new ArrayList<>();
|
|
|
|
for (Iterator<JsonNode> it = root.elements(); it.hasNext(); ) {
|
|
|
|
JsonNode node = it.next();
|
|
|
|
int found = 0;
|
|
|
|
for (Iterator<String> iter = node.fieldNames(); iter.hasNext(); ) {
|
|
|
|
String fieldName = iter.next();
|
|
|
|
if (fieldName.equals(key)) {
|
|
|
|
if (node.get(fieldName).asText().equals(value) || node.get(fieldName).asText().startsWith(value)) {
|
2020-06-12 16:25:53 +02:00
|
|
|
if (parent) {
|
|
|
|
nodes.add(root);
|
|
|
|
} else {
|
|
|
|
nodes.add(node);
|
|
|
|
}
|
2020-03-20 17:20:22 +01:00
|
|
|
found++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
if (found == 0) {
|
2020-06-12 16:25:53 +02:00
|
|
|
nodes.addAll(findNodes(node, key, value, parent));
|
2020-03-20 17:20:22 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nodes;
|
|
|
|
}
|
|
|
|
}
|