欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

json转树,json层级展开为list

程序员文章站 2022-06-16 11:06:36
...

将json转成树状结构,然后展开成list,有key就取key,没key就取value,通过递归实现

JSONNode 是节点类,其中的key就是json的key,value是如果没有子节点的json的value

建这俩类唯一的好处就是把jsonobject格式化成一个确定的类,方便递归,就不用每次获取value的时候多次遍历看下面有多少个子节点,关键不知道层数,不方便递归

children是子节点(可以为另一个json,或者json array)

public class JSONNode {
    private String key;

    private int level;

    private String value;

    private List<JSONNode> children;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public List<JSONNode> getChildren() {
        return children;
    }

    public void setChildren(List<JSONNode> children) {
        this.children = children;
    }
}

jsontree 通过递归遍历 将json的key和value(如果有的话),及其子节点的递归打印出来

注:

json转树,不符合标准的树定义,有两点需要转换一下,方便递归

1,root没有key,key就暂定为"root",

2,如果某节点为 jsonarray,key就暂定为"i'm arr"

 

public class JSONTree {
    public static JSONNode createJSONTree(Object value, String key, int level) {
        JSONNode node = new JSONNode();
        node.setKey(key);
        node.setLevel(level);
        level++;

        if (value instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) value;
            Set<String> keySet = jsonObject.keySet();
            List<JSONNode> childrenList = new LinkedList<>();
            for (String keyInner : keySet) {
                JSONNode childNode = createJSONTree(jsonObject.get(keyInner), keyInner, level);
                childrenList.add(childNode);
            }
            node.setChildren(childrenList);
        } else if (value instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) value;
            List<JSONNode> childrenList = new LinkedList<>();
            for (int index = 0; index < jsonArray.size(); index++) {
                JSONNode childNode = createJSONTree(jsonArray.get(index), "i'm arr", level);
                childrenList.add(childNode);
            }
            node.setChildren(childrenList);
        } else {
            node.setValue(String.valueOf(value));
            node.setChildren(null);
        }
        return node;
    }


    public static LinkedList<LinkedList<String>> binaryTreePaths(JSONNode root) {
        LinkedList<LinkedList<String>> paths = new LinkedList();
        getPath(root, new LinkedList<>(), paths);
        return paths;
    }


    public static void getPath(JSONNode root, LinkedList<String> path, LinkedList<LinkedList<String>> paths) {
        if (root != null) {
            path.add(root.getKey());
            if (root.getChildren() == null) {
                LinkedList<String> dist = new LinkedList<>();
                dist.addAll(path);
                dist.add(root.getValue());
                paths.add(dist);
            } else {
                List<JSONNode> list = root.getChildren();
                for (JSONNode node : list) {
                    LinkedList<String> dist = new LinkedList<>();
                    dist.addAll(path);
                    getPath(node, dist, paths);
                }
            }
        }
    }

    public static void main(String[] args) {
        JSONObject json = new JSONObject();

        JSONObject json1 = new JSONObject();
        json1.put("status", 1);
        json1.put("error", "001");
        json1.put("msg", "err1");
        json.put("1", json1);

        JSONObject json2 = new JSONObject();
        json2.put("status", 1);
        json2.put("error", "002");
        json2.put("msg", "err2");
        json.put("2", json2);

        JSONArray json3 = new JSONArray();
        json3.add(json1);
        json3.add(json2);

        json.put("3", json3);

        JSONNode root = JSONTree.createJSONTree(json, "root", 0);


        LinkedList<LinkedList<String>> paths = binaryTreePaths(root);

        paths.forEach(list -> {
            list.stream().map(s -> s + " ").forEach(System.out::print);
            System.out.println();
        });


    }

其中数据结构部分如下图所示

json转树,json层级展开为list

 

 

如代码所示,输入为

{
	"1": {
		"msg": "err1",
		"error": "001",
		"status": 1
	},
	"2": {
		"msg": "err2",
		"error": "002",
		"status": 1
	},
	"3": [{
		"msg": "err1",
		"error": "001",
		"status": 1
	}, {
		"msg": "err2",
		"error": "002",
		"status": 1
	}]
}

输出为:

root 1 msg err1 
root 1 error 001 
root 1 status 1 
root 2 msg err2 
root 2 error 002 
root 2 status 1 
root 3 i'm arr msg err1 
root 3 i'm arr error 001 
root 3 i'm arr status 1 
root 3 i'm arr msg err2 
root 3 i'm arr error 002 
root 3 i'm arr status 1