EasyUI Tree是一款比較常用的樹(shù)形控件,可以通過(guò)json格式的數(shù)據(jù)渲染生成樹(shù)形結(jié)構(gòu)界面。在Java后端開(kāi)發(fā)中,我們可以利用JavaBean和Gson等庫(kù)實(shí)現(xiàn)生成EasyUI Tree所需的json數(shù)據(jù)。
使用JavaBean定義一個(gè)樹(shù)形節(jié)點(diǎn)和節(jié)點(diǎn)中的子節(jié)點(diǎn)信息:
public class TreeNode { private int id; private String text; private List<TreeNode> children; public TreeNode(int id, String text, List<TreeNode> children) { this.id = id; this.text = text; this.children = children; } // 省略getter和setter方法 }
通過(guò)以上JavaBean,可以生成如下的一段json數(shù)據(jù):
{ "id": 1, "text": "父節(jié)點(diǎn)", "children": [ { "id": 2, "text": "子節(jié)點(diǎn)1", "children": null }, { "id": 3, "text": "子節(jié)點(diǎn)2", "children": [ { "id": 4, "text": "孫子節(jié)點(diǎn)1", "children": null }, { "id": 5, "text": "孫子節(jié)點(diǎn)2", "children": null } ] } ] }
接下來(lái),需要使用Gson將JavaBean轉(zhuǎn)換為json字符串:
List<TreeNode> nodeList = new ArrayList<>(); nodeList.add(new TreeNode(1, "父節(jié)點(diǎn)", Arrays.asList( new TreeNode(2, "子節(jié)點(diǎn)1", null), new TreeNode(3, "子節(jié)點(diǎn)2", Arrays.asList( new TreeNode(4, "孫子節(jié)點(diǎn)1", null), new TreeNode(5, "孫子節(jié)點(diǎn)2", null) )) ))); Gson gson = new Gson(); String json = gson.toJson(nodeList); System.out.println(json);
輸出的json數(shù)據(jù)就是我們前文所示的那段數(shù)據(jù)。最后,將這段json數(shù)據(jù)傳到EasyUI Tree的data屬性中,即可在前端渲染出樹(shù)形結(jié)構(gòu)。