
org.tinygroup.tinyscript.tree.impl.DataNodeUtil Maven / Gradle / Ivy
The newest version!
package org.tinygroup.tinyscript.tree.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.tinygroup.tinyscript.tree.DataNode;
import org.tinygroup.tinyscript.tree.impl.TreeDataNode.DataNodeArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 树型节点工具类
* @author yancheng11334
*
*/
public final class DataNodeUtil {
private DataNodeUtil(){
}
/**
* 将TreeDataNode转换JSON字符串
* @param tree
* @return
*/
public static String toJson(TreeDataNode tree){
JSONObject json = new JSONObject();
convertJson(tree,json);
return json.toJSONString();
}
/**
* 将JSON字符串转换TreeDataNode
* @param json
* @return
*/
public static TreeDataNode readJson(String jsonStr){
JSONObject json = JSON.parseObject(jsonStr);
TreeDataNode tree = new TreeDataNode();
for(Entry entry:json.entrySet()){
convertJsonNode(tree,entry);
}
return tree;
}
private static void convertJsonNode(TreeDataNode tree,Entry entry){
if(entry.getValue()!=null){
if(entry.getValue() instanceof JSONArray){
TreeDataNode node = new TreeDataNode();
JSONArray array = (JSONArray)entry.getValue();
for(int i=0;i jsonEntry:json.entrySet()){
convertJsonNode(node,jsonEntry);
}
tree.addNode(entry.getKey(), node);
}
}else if(entry.getValue() instanceof JSONObject){
TreeDataNode node = new TreeDataNode();
JSONObject json = (JSONObject)entry.getValue();
for(Entry jsonEntry:json.entrySet()){
convertJsonNode(node,jsonEntry);
}
tree.addNode(entry.getKey(), node);
}else{
tree.put(entry.getKey(), entry.getValue());
}
}else{
tree.put(entry.getKey(), entry.getValue());
}
}
private static void convertJson(TreeDataNode tree,JSONObject json){
if(tree==null || json==null){
return;
}
Map maps = (Map) tree.getAttributes();
for(Entry entry:maps.entrySet()){
if(entry.getValue()!=null && entry.getValue() instanceof DataNodeArray){
//设置子节点
DataNodeArray array = (DataNodeArray) entry.getValue();
List children = array.getChildren();
if(array.isArray() || array.getLength()>1){
//节点列表
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy