json树结构转化普通json数据

树json数据结构
在这里插入图片描述

转化后的普通json数据格式
在这里插入图片描述

方法一

function treeTransArray(tree, key) {//通过树结构返回普通json数组
            return tree.reduce(function(con, item) {
                var callee = arguments.callee;
                con.push(item);
                if (item[key] && item[key].length >0)
                    item[key].reduce(callee, con);
                return con;
            }, []).map(function(item){
            item[key] = [];
            return item;
        })
}

严格模式下调用此方法可能会报错 arguments.callee;
可修改如下

function treeTransArray(tree, key) {//通过树结构返回普通json数组
        return tree.reduce(function itemTree(con, item) {
              con.push(item);
              if (item[key] && item[key].length >0)
                  item[key].reduce(itemTree, con);
              return con;
          }, []).map(function(item){
          item[key] = [];
          return item;
      })
}
**调用方法**

var selList=[{}] // 创建一个数组 默认的第一个元素为对象
selList[0]=node //node 为树形json , childrenList为 key
var dataArr=treeTransArray(selList,'childrenList');

方法二

使用ztree 自带方法
下载ztree.js ;

```javascript
var newTree=$.fn.zTree.getZTreeObj("TargetTree");//获取树
var Nodes=newTree.getNodes();//拿到树形的json树节点(最上一张图的节点)
var act=newTree.transformToArray(Nodes); //ztree自带将json 树结构转化普通json的方法

反转 普通json转化树形json

//“childData” 为children 数组;
//idstr 自身code id
//pidstr 父级的code或者id
//list 普通形式的数组

function arrayTransTree(list,idstr,pidstr){ 
         try {
            let result = [],temp = {};  
            for(let i = 0; i < list.length; i++){  
                temp[list[i][idstr]]=list[i];//将nodes数组转成对象类型  
            }  
            for(let j=0; j<list.length; j++){  
                let tempVp = temp[list[j][pidstr]]; //获取每一个子对象的父对象  
                if(tempVp){//判断父对象是否存在,如果不存在直接将对象放到第一层  
                    if(!tempVp["childData"]) tempVp["childData"] = [];//如果父元素的childData对象不存在,则创建数组  
                    tempVp["childData"].push(list[j]);//将本对象压入父对象的childData数组  
                }else{  
                    result.push(list[j]);//将不存在父对象的对象直接放入一级目录  
                }  
            }  
            return result;  
         } catch (error) {
             console.log(error)
         }
    },
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是将Java中的List转换为JSON树结构的示例代码: ```java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.List; public class ListToJSONTree { public static void main(String[] args) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); // 创建一个List,用于模拟数据 List<Node> nodeList = List.of( new Node(1, "root", null), new Node(2, "node1", 1), new Node(3, "node2", 1), new Node(4, "node3", 2), new Node(5, "node4", 3) ); // 将List转换为JSON树结构 ArrayNode rootNode = objectMapper.createArrayNode(); for (Node node : nodeList) { ObjectNode nodeObject = objectMapper.createObjectNode(); nodeObject.put("id", node.getId()); nodeObject.put("name", node.getName()); nodeObject.put("parentId", node.getParentId()); addChildNode(rootNode, nodeObject, node.getParentId()); } // 输出转换后的JSON树结构 System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode)); } private static void addChildNode(ArrayNode rootNode, ObjectNode nodeObject, Integer parentId) { for (int i = 0; i < rootNode.size(); i++) { ObjectNode parentObject = (ObjectNode) rootNode.get(i); if (parentObject.get("id").asInt() == parentId) { if (!parentObject.has("children")) { parentObject.putArray("children"); } ArrayNode childrenArray = (ArrayNode) parentObject.get("children"); childrenArray.add(nodeObject); return; } else if (parentObject.has("children")) { addChildNode((ArrayNode) parentObject.get("children"), nodeObject, parentId); } } } static class Node { private final Integer id; private final String name; private final Integer parentId; public Node(Integer id, String name, Integer parentId) { this.id = id; this.name = name; this.parentId = parentId; } public Integer getId() { return id; } public String getName() { return name; } public Integer getParentId() { return parentId; } } } ``` 这个例子中,我们通过创建一个List来模拟数据,然后将这个List转换为JSON树结构。在转换的过程中,我们使用了Jackson库来进行JSON的序列化和反序列化。我们使用ObjectMapper来创建JSON对象和数组,使用ObjectNode和ArrayNode来表示JSON对象和数组。我们遍历List中的每一个元素,将其转换为JSON对象,并且添加到相应的父节点下。在添加子节点时,我们使用递归函数addChildNode来遍历JSON树结构,找到相应的父节点并添加子节点。最后,我们使用ObjectMapper将JSON树结构转换为字符串,并且输出到控制台上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值