我在数据库中有一个表,其结构和数据如下:
我想通过java从该表中获取JSON树数据:
[
{
"id":"null",
"text":"Text1",
"children":[
{
"id":3,
"text":"Text3",
"children":[
]
},
{
"id":4,
"text":"Text4",
"children":[
{
"id":10,
"text":"Text10",
"children":[
]
}
]
},
{
"id":6,
"text":"Text6",
"children":[
]
}
]
},
...
]
有人可以帮我吗?
谢谢。:)
答案 0 :(得分:2)
按照下面的步骤进行操作
:public class NodeBean implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String text; private List children; }
public class NodeInfoBean { private Integer id; private String text; }
private List<NodeInfoBean> getData(Integer parentId) { // select id, text from table where parent_id = :parentId }
private List<NodeBean> buildNode(Integer parentId) { List<NodeBean> result = new ArrayList<>(); List<NodeInfoBean> data = getData(parentId); for (NodeInfoBean nodeInfo : data){ NodeBean node = NodeBean .builder() .id(nodeInfo.getId()) .text(nodeInfo.getText()) .children(buildNode(nodeInfo.getId())) .build(); result.add(node); } return result; }
List<NodeBean> data = buildNode(null); return new ObjectMapper().writeValueAsString(data);
[{ "id": 1, "text": "Text1", "children": [ { "id": 3, "text": "Text3", "children": [] }, { "id": 4, "text": "Text4", "children": [ { "id": 10, "text": "Text10", "children": [] } ] }, { "id": 6, "text": "Text6", "children": [] } ]}, { "id": 2, "text": "Text2", "children": [ { "id": 5, "text": "Text5", "children": [ { "id": 8, "text": "Text8", "children": [] }, { "id": 9, "text": "Text9", "children": [] } ] } ]}]