Add get Parent values on json Searcher

This commit is contained in:
George Kalampokis 2022-03-02 10:56:28 +02:00
parent 5ea8b9b964
commit 608c4f3fc0
1 changed files with 29 additions and 1 deletions

View File

@ -1,10 +1,10 @@
package eu.eudat.logic.utilities.json;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class JsonSearcher {
@ -38,4 +38,32 @@ public class JsonSearcher {
}
return nodes;
}
public static List<String> getParentValues(JsonNode root, String childValue, String key) {
List<String> values = new LinkedList<>();
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(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;
}
}