Home > Mobile >  How do I get the path of a jackson JsonNode
How do I get the path of a jackson JsonNode

Time:04-05

I have a json that looks something like this

{
    "a": {
        "b": [
            {
                "c": {
                    "d": [{ "f": "value" }]
                }
            },
            {
                "c": {
                    "d": [{ "f": "value" }]
                }
            }
        ]
    }
}

I'm looping the data inside b using the following code, then getting the array at d again in a nested loop

for (JsonNode abNode : rootNode.at("/a/b")) {
    for (JsonNode cdNode : abNode.at("/c/d")) {
        //cdNode.get("f")
    }
}

Inside the for loop how can I get the path of something like node.get("f") so that I would get /a/b/0/c/d/0/f and then /a/b/1/c/d/0/f? Does jackson have something to get this or another library? The only thing I can think of right now is just switching to a for i=0 loop

CodePudding user response:

What you are trying to do is also called as Xpath in technical terms. It is used for html, xml based languages as well as now available in json

You can try jsonpath for this case:

https://www.baeldung.com/guide-to-jayway-jsonpath https://github.com/json-path/JsonPath

CodePudding user response:

Google's popular GSON library has a method, namely getPath, maybe useful for your purpose:

String json = "...";
JsonReader reader = new JsonReader(new StringReader(json));
System.out.println(reader.getPath());
  • Related