Reputation: 840
I'm trying to retrieve the json path of a value from a json string with jackson. As I couldn't find any function inside jackson giving me this result, I wanted to create my own function.
So I made this function :
public static String getJsonPath(Map.Entry<String, JsonNode> jsonNode, String valueSearched) {
String res = "";
String key = jsonNode.getKey();
JsonNode value = jsonNode.getValue();
if (value.isValueNode() && value.equals(valueSearched)) { // Here the value change to a ValueNode and the key weirdly equals to "".
return res + key;
} else {
if (value.isContainerNode()) {
if (value.isObject()) {
Iterator<Map.Entry<String, JsonNode>> elements = value.fields();
while (elements.hasNext()) {
Map.Entry<String, JsonNode> element = elements.next();
res += "." + element.getKey() + generateJsonPathArgumentFromJson(element, valueSearched);
}
} else {
int i = 0;
ArrayNode arrayNode = (ArrayNode) jsonNode;
Iterator<Map.Entry<String,JsonNode>> elements = arrayNode.fields();
while (elements.hasNext()) {
Map.Entry<String, JsonNode> element = elements.next();
i++;
res += "(" + i + ")" + generateJsonPathArgumentFromJson(element, valueSearched);
}
}
}
}
return "";
}
Why the key gets equal to "" after the first if ? Or there's a better way to construct a json path for a specific value ?
Upvotes: 4
Views: 4311
Reputation: 840
Just get the solutions :
protected static String generateJsonPathArgumentFromJson(JsonNode jsonNode, String valueSearched) {
if (jsonNode.isValueNode() && !jsonNode.asText().equals(valueSearched)) {
return null;
} else {
if (jsonNode.isContainerNode()) {
if (jsonNode.isObject()) {
Iterator<Map.Entry<String, JsonNode>> elements = jsonNode.fields();
while (elements.hasNext()) {
Map.Entry<String, JsonNode> element = elements.next();
String res = generateJsonPathArgumentFromJson(element.getValue(), valueSearched);
if (res != null) {
return "." + element.getKey() + res;
}
}
} else {
int i = 0;
Iterator<JsonNode> elements = jsonNode.elements();
while (elements.hasNext()) {
JsonNode element = elements.next();
String res = generateJsonPathArgumentFromJson(element, valueSearched);
if (res != null) {
return "(" + i + ")" + res;
}
i++;
}
}
}
}
return "";
}
I'm sure there's better way to do, but at least it works :)
Upvotes: 2