package eu.eudat.file.transformer.utils.json; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class JsonSearcher { public static List findNodes(JsonNode root, String key, String value) { return findNodes(root, key, value, false); } public static List findNodes(JsonNode root, String key, String value, boolean parent) { List nodes = new ArrayList<>(); for (Iterator it = root.elements(); it.hasNext(); ) { JsonNode node = it.next(); int found = 0; for (Iterator 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)) { if (parent) { nodes.add(root); } else { nodes.add(node); } found++; } else if(node.get(fieldName).isArray()){ for(JsonNode item: node.get(fieldName)){ if(item.asText().equals(value) || item.asText().startsWith(value)){ if (parent) { nodes.add(root); } else { nodes.add(node); } found++; } } } } } if (found == 0) { nodes.addAll(findNodes(node, key, value, parent)); } } return nodes; } public static List getParentValues(JsonNode root, String childValue, String key) { List values = new LinkedList<>(); for (Iterator it = root.elements(); it.hasNext(); ) { JsonNode node = it.next(); int found = 0; for (Iterator iter = node.fieldNames(); iter.hasNext(); ) { String fieldName = iter.next(); if (fieldName.equals(key)) { if (node.get(fieldName).asText().equals(childValue) || node.get(fieldName).asText().startsWith(childValue)) { values.add(childValue); found++; } } } if (found == 0) { values.addAll(getParentValues(node, childValue, key)); if (!values.isEmpty() && node.has(key)) { values.add(node.get(key).asText()); values.remove(childValue); } } } return values; } }