将目录作为字符串转换为json数组节点

时间:2016-10-07 00:22:16

标签: java json

将此列表作为字符串数组:

Cars/Truck/Regular
Cars/Truck/4x4/Lifted
Cars/Jeep/4x4
Cars/Convertable

如何将其解析为json,如:

[{"name":"Cars","nodes":[{"name":"Truck","nodes":[{"name":"Regular","nodes":[]},{"name":"4x4","nodes":[{"name":"Lifted","nodes":[]}]}]},{"name":"Jeep","nodes":[{"name":"4x4","nodes":[]}]},{"name":"Convertable","nodes":[]}]}]

到目前为止,这是我所有的递归过程。现在必须弄清楚节点类的部分。

String[] li = new String[4];
li[0] = "Cars/Truck/Regular";
li[1] = "Cars/Truck/4x4/Lifted";
li[2] = "Cars/Jeep/4x4";
li[3] = "Cars/Convertable";
doAll(li);
public void doAll(String[] files) {
    try {
        for (String file : files) {
            String[] f = file.split("/");
            if (f.length>1) {
                logger.info("directory:"+file);
                f = (String[]) ArrayUtils.removeElement(f, f[0]);
                String temp = "";
                for(String ff : f) temp=temp+"/"+ff;
                temp = temp.replaceFirst("/", "");
                doAll(new String[]{temp});
            } else if(f.length==1){
                logger.info("file:"+file);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

产生

directory:Cars/Truck/Regular
directory:Truck/Regular
file:Regular
directory:Cars/Truck/4x4/Lifted
directory:Truck/4x4/Lifted
directory:4x4/Lifted
file:Lifted
directory:Cars/Jeep/4x4
directory:Jeep/4x4
file:4x4
directory:Cars/Convertable
file:Convertable

1 个答案:

答案 0 :(得分:0)

可能你必须先创建一个结构来保存这些数据,然后将所有数据提供给结构,然后将结果序列化为json字符串。伪代码类似于:

class Node {
  String name;
  List<Node> nodes;    // sub nodes

  /*
   Add new node under current node.
  */
  public void addNode(Node node) {...}
}

你从第一个值开始说Car来创建结构,然后尝试递归地找到左侧值/ Truck,/ Truck / Regular在它的sub(或sub子节点)节点。如果找到,则不执行任何操作,否则您将创建一个新的子节点并将其添加到上次找到的节点。