上篇文章为如何将文件夹遍历成yml的结构,并转成json字符串,本篇主要讲解如何将转换后的字符串(不规则对象)解析成可直接插入数据库的树形对象。
上篇文章地址:java 遍历文件夹目录树形结构并在控制台输出且保存到本地文件(生成可直接解析的yml文件)_再写一行代码就下班的博客-CSDN博客
public class JsonTest {
public static void main(String[] args) {
String json = "[\n" +
" {\n" +
" \"G\": [\n" +
" {\n" +
" \"work\": [\n" +
" {\n" +
" \"1231231123\": [\n" +
" {\n" +
" \"项目\": [\n" +
" {\n" +
" \"11项目\": [\n" +
" {\n" +
" \"文档\": [\n" +
" {\n" +
" \"接口\": [\n" +
" \"1.png\",\n" +
" \"2.png\",\n" +
" \"3.png\",\n" +
" \"4.png\",\n" +
" \"5.png\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"odersql\": [\n" +
" \"12323.png\",\n" +
" \"23312312.png\",\n" +
" \"212.png\",\n" +
" \"1222.png\",\n" +
" \"123WE.png\",\n" +
" \"W.png\",\n" +
" \"1.png\",\n" +
" \"121DD.png\",\n" +
" \"QWEQ.png\",\n" +
" \"QWE.png\",\n" +
" \"6_getUnhandle_getChangeOrderTrend.png\",\n" +
" \"2231SS.png\",\n" +
" \"122是.png\",\n" +
" \"123.png\"\n" +
" ]\n" +
" },\n" +
" \"字典(1).xlsx\",\n" +
" \"命令.xlsx\",\n" +
" \"项汇总.docx\",\n" +
" \"流程图.png\",\n" +
" \"使用手册doc.doc\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
"]";
try {
JSONArray jsonArray = new JSONArray(json);//将对象转换成json数组
HashSet<FileNode> array = getArray(jsonArray, null);//递归封装tree
for (FileNode fileNode : array) {
System.out.println("fileNode--->>>" + fileNode);
}
System.out.println();
} catch (JSONException e) {
e.printStackTrace();
}
}
private static HashSet<FileNode> getArray(JSONArray jsonArray, String parentId) {
int length = jsonArray.length();
HashSet<FileNode> hashSet = new HashSet<>();
// ArrayList<FileNode> list = new ArrayList<>();
for (int i = 0; i < length; i++) {//变量每个文件夹
FileNode fileNode = new FileNode();
fileNode.setParentCode(parentId);
String code = UUID.randomUUID().toString();
fileNode.setCode(code);
try {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);//文件夹
if (jsonObject.keys().hasNext()) {
String nodeName = (String) jsonObject.keys().next();
fileNode.setName(nodeName);
System.out.println(nodeName);
JSONArray o = (JSONArray) jsonObject.get(nodeName);
if (o.length() > 0) {
HashSet<FileNode> array = getArray(o, code);
hashSet.addAll(array);
}
}
} catch (Exception e) {
String nodeName = null;
try {
nodeName = (String) jsonArray.get(i);//文件
fileNode.setName(nodeName);
} catch (Exception e1) {
System.out.println("出现异常");
}
System.out.println(nodeName);
}
hashSet.add(fileNode);
}
return hashSet;
}
}