How can you get JSON Path?

Given a JSON sample:

{
  "hello" : "wolrd",
  "arrayField" : ["one", "two", "three"],
  "mapField" : {
    "name" : "john",
    "lastName" : "doe" 
  }
}

Is there an environment in Java that will help me get the structure of the JSON path from the JSON tree? Something like this:

$.hello
$.arrayField[0]
$.arrayField[1]
$.arrayField[2]
$.mapField.name
$.mapField.lastName

EDIT:

I already encoded the first approach using quickxml Jackson. But I would like to know if there is something more reliable / flexible.

   final JsonNode rootNode = mapper.readValue(jon, JsonNode.class);
    printFieldKeys(rootNode, "$");

    private static void printFieldKeys(JsonNode rootNode, String parent) {
        final Iterator<Entry<String, JsonNode>> fieldIt = rootNode.fields();
        while (fieldIt.hasNext()) {
            final Entry<String, JsonNode> next = fieldIt.next();
            final JsonNode value = next.getValue();
            final String path = parent + "." + next.getKey();

            if (value.isValueNode()) {
                System.out.println(path + " = " + value.asText());
            } else  {
                System.out.println(path);
            }


            if (value.isArray()) {
                for (int i = 0; i < value.size(); i++) {
                    printFieldKeys(value.get(i), path + "[" + i + "]");
                }
            } else {
                printFieldKeys(value, path);
            }

        }
    }
+4
source share
1 answer

Take a look at this library: https://github.com/jayway/JsonPath

I believe that he does exactly what you want. :)

+1
source

All Articles