给定一个示例 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
编辑:
我已经使用 fasterxml 的 Jackson 编写了第一种方法。但我想知道是否有更强大/更灵活的东西。
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
我相信它完全符合您的要求。 :)
关于java - 你怎么能得到JSON路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149396/