I have multiple complex (Jackson) JsonNode structures which I need to find a value in. The problem is very similar to: how to parse json array value using json node and Jackson JsonNode Serialization.
So I would like to find a value inside a JsonNode with the following limitation: The context is provided by (Cucumber) tests. e.g. 'Inside "title/configurations/relation" I see the value "a" ' see example below.
The code I've tried to use:
public JsonNode findNodeInPath (String path, JsonNode parent) {
int firstSlash = path.indexOf("/");
if (parent == null) {
return null;
}
else {
String nextNodeName = firstSlash == -1 ? path : path.substring(0, firstSlash);
if (parent.isObject()) {
return findNodeInPath(firstSlash == -1 ? path : path.substring(firstSlash + 1), parent.findValue(nextNodeName));
}
else { // parent is array
if (parent.has(path)) {
return parent;
}
for (JsonNode node : parent) {
JsonNode nextNode = node.findValue(nextNodeName);
if (nextNode != null) {
return findNodeInPath(firstSlash == -1 ? path : path.substring(firstSlash + 1), nextNode);
}
}
}
return null; // not found
}
}
But that doesn't work because when I get to a JsonArray with strings only (like "relation" below) Jackson doesn't let me access the text inside it.
I don't want to create a POJO for each JsonNode because:
The variance between nodes is very big. I can't see any object that will fit even most of the configurations I have.
This is used for testing only. The structures as they are, just sit on the database. I wouldn't like to create objects solely for testing purposes.
An example of a JsonNode I have:
{
"title": [
{
"configuration": [
{
"product1": {
"id": "id1",
"name": [
{
"locale": "en_US",
"value": "value1"
}
]
},
"configured": true,
"relation": ["a","b","c"],
"relation2": []
}
]
}
]
}
I apologize for the long question, any help (from any direction) would be greatly appreciated.