java – 如何获得JSON路径?

给出一个示例
JSON

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

Java中是否有一个框架可以帮助我从JSON树中获取JSON路径结构?与此类似的东西:

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

编辑:

我已经使用fastxml的杰克逊编写了第一种方法.但我想知道是否有更强大/更灵活的东西.

   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);
            }

        }
    }

最佳答案 看看这个库:
https://github.com/jayway/JsonPath

我相信它完全符合你的要求. 🙂

点赞