我正在开发一个项目,我需要在Java中解析JSON并显示JSON密钥/节点的分层路径,如下所述。
我正在使用Jackson API在Java中开发此程序,但我无法获得任何现成的API,这将返回JSON当前键/节点的分层路径。
JSON数据 -
{“tomcat-users”:
{
“role”:[
{“@rolename”:”manager-gui”},
{“@rolename”:”manager-script”},
{“@rolename”:”manager-jmx”},
{“@rolename”:”manager-status”}
],
”user”:{
“@username”:”admin”,
”@roles”:”manager-gui,manager-script”,
”@password”:”admin”
}
}
}
输出应该像 -
Column 1 Column 2
---------------------------------------------------------------------------
tomcat-users -> role[1] -> @rolename manager-gui
tomcat-users -> role[2] -> @rolename manager-script
tomcat-users -> role[3] -> @rolename manager-jmx
tomcat-users -> role[4] -> @rolename manager-status
tomcat-users -> user -> @username admin
tomcat-users -> user -> @roles manager-gui,manager-script
tomcat-users -> user -> @password admin
任何人都可以告诉我,他们的任何API是否会让我回到原点?
我的Java代码 -
public static void generateJsonPath(JsonNode node) {
Iterator<String> fieldNames = node.getFieldNames();
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
JsonNode fieldValue = node.get(fieldName);
if (fieldValue.isObject()) {
System.out.println(fieldName + " -> ");
generateJsonPath(fieldValue);
} else if(fieldValue.isArray()) {
System.out.println(fieldName + " -> ");
Iterator<?> iterator = fieldValue.getElements();
while(iterator.hasNext()) {
generateJsonPath((JsonNode) iterator.next());
}
} else {
String value = fieldValue.asText();
System.out.println(fieldName + " : " + value);
}
}
}
Java代码结果 -
tomcat-users ->
role ->
@rolename : manager-gui
@rolename : manager-script
@rolename : manager-jmx
@rolename : manager-status
user ->
@username : root
@password : root
@roles : manager-gui,manager-script,manager-jmx,manager-status