Return empty list when node is an object

This commit is contained in:
Xavi Aracil 2022-11-25 13:55:08 +01:00
parent 82ab70eaf9
commit f4f44f61ff

View File

@ -17,11 +17,11 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
public class JsonNodeUtil { public class JsonNodeUtil {
public static List<JsonNode> asNodeList(JsonNode root, String jsonPath, JsonPathEvaluator evaluator) { public static List<JsonNode> asNodeList(JsonNode root, String jsonPath, JsonPathEvaluator evaluator) {
List<JsonNode> list = new ArrayList<>(); List<JsonNode> list = new ArrayList<>();
ArrayNode array = evaluator.eval(jsonPath, root); ArrayNode array = evaluator.eval(jsonPath, root);
for(JsonNode node : array) { for(JsonNode node : array) {
if(!(node instanceof ArrayNode)) { if(!(node instanceof ArrayNode)) {
list.add(node); list.add(node);
} else { } else {
ArrayNode values = (ArrayNode) node; ArrayNode values = (ArrayNode) node;
for(JsonNode value : values) { for(JsonNode value : values) {
@ -31,28 +31,31 @@ public class JsonNodeUtil {
} }
return list; return list;
} }
public static List<String> asStringList(JsonNode node) { public static List<String> asStringList(JsonNode node) {
if(!(node instanceof ArrayNode)) { if(!(node instanceof ArrayNode)) {
if (node.isObject()) {
return List.of();
}
return List.of(node.asText()); return List.of(node.asText());
} else { } else {
ArrayNode arrayNode = (ArrayNode)node; ArrayNode arrayNode = (ArrayNode)node;
return StreamSupport return StreamSupport
.stream(arrayNode.spliterator(), false) .stream(arrayNode.spliterator(), false)
.map(n->n.asText().strip()) .map(n->n.asText().strip())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} }
public static List<JsonNode> asNodeList(JsonNode node) { public static List<JsonNode> asNodeList(JsonNode node) {
if(node == null) return null; if(node == null) return null;
if(!(node instanceof ArrayNode)) { if(!(node instanceof ArrayNode)) {
return List.of(node); return List.of(node);
} else { } else {
ArrayNode arrayNode = (ArrayNode)node; ArrayNode arrayNode = (ArrayNode)node;
return StreamSupport return StreamSupport
.stream(arrayNode.spliterator(), false) .stream(arrayNode.spliterator(), false)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} }
} }