# 算法题！请问如何将一段json转成这样的树？

{
id: 1,
name: "上海XX网络公司",
parentid: 0
},
{
id: 2,
name: "总裁办",
parentid: 1
},
{
id: 3,
name: "产品部",
parentid: 2
},
{
id: 4,
name: "设计部",
parentid: 1
}

var tree = [{
label: "节点名",
value: "id",
children: [
{
label: "节点名",
value: "id",
children: [
{
label: "节点名",
value: "id"
}
]
}
]
}];

0

0
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
* Created by Rayn on 2014/9/18.
*/
public class JSONParseDemo
{
public static void main(String[] args)
{
List<Nodes> listNodes = JSONObject.parseArray("[{id: 1, name: \"上海XX网络公司\", parentid: 0 },{ id: 2, name: \"总裁办\", parentid: 1 },{ id: 3, name: \"产品部\", parentid: 2},{id: 4,name: \"设计部\",parentid: 1}]", Nodes.class);

List<TreeNodes> treeNodeses = new ArrayList<TreeNodes>();
for(int j = 0, len = listNodes.size(); j < len; j++)
{
Nodes childrenNode = listNodes.get(j);
if(childrenNode.getParentid() == 0)
{
TreeNodes chi = new TreeNodes();
chi.setLabel(childrenNode.getName());
chi.setValue(childrenNode.getId() + "");
chi.setChildren(getChildrenNode(treeNodeses, listNodes, childrenNode.getId()));
}
}

System.out.println(JSON.toJSON(treeNodeses));
}

public static List<TreeNodes> getChildrenNode(List<TreeNodes> treeNodeses, List<Nodes> listNodes, int id)
{
List<TreeNodes> temp = new ArrayList<TreeNodes>();
for(int j = 0, len = listNodes.size(); j < len; j++)
{
TreeNodes chi = new TreeNodes();
Nodes childrenNode = listNodes.get(j);
if (childrenNode.getParentid() == id)
{
chi.setLabel(childrenNode.getName());
chi.setValue(childrenNode.getId() + "");
chi.setChildren(getChildrenNode(treeNodeses, listNodes, childrenNode.getId()));
}
}
return temp;
}
}

class TreeNodes
{
private String label;

private String value;

private List<TreeNodes> children;

public String getLabel()
{
return label;
}

public void setLabel(String label)
{
this.label = label;
}

public String getValue()
{
return value;
}

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

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

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

class Nodes
{
private String name;

private int id;

private int parentid;

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public int getParentid()
{
return parentid;
}

public void setParentid(int parentid)
{
this.parentid = parentid;
}

}

我试了试，，，，凑合着可以用，，你看看是否满足你的要求！！！