maven的pom文件
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
</dependencies>
实现代码
public static List<String> getListJson(JSONObject jsonObject) {
// 获取到所有jsonpath后,获取所有的key
List<String> jsonPaths = JSONPath.paths(jsonObject).keySet()
.stream()
.collect(Collectors.toList());
//去掉根节点key
List<String> parentNode = new ArrayList<>();
//根节点key
parentNode.add("/");
//循环获取父节点key,只保留叶子节点
for (int i = 0; i < jsonPaths.size(); i++) {
if (jsonPaths.get(i).lastIndexOf("/") > 0) {
parentNode.add(jsonPaths.get(i).substring(0, jsonPaths.get(i).lastIndexOf("/")));
}
}
//remove父节点key
for (String parentNodeJsonPath : parentNode) {
jsonPaths.remove(parentNodeJsonPath);
}
List<String> jsonPathList = new ArrayList<>();
Iterator<String> jsonPath = jsonPaths.iterator();
//将/替换为点.
while (jsonPath.hasNext()) {
jsonPathList.add(jsonPath.next().replaceFirst("/", "").replaceAll("/", "."));
}
//排序
Collections.sort(jsonPathList);
return jsonPathList;
}
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
JSONPath.set(jsonObject,"data.person","个人");
JSONPath.set(jsonObject,"data.student.age","20");
JSONPath.set(jsonObject,"data.student.name","张三");
List<String> listJsonPath = getListJson(jsonObject);
for(String jsonPath:listJsonPath){
System.out.println(jsonPath);
}
}
执行结果
data.person
data.student.age
data.student.name
扩展
1.可通过jsonpath去获取json的value
JSONPath.eval(jsonObject,“data.student.name”)