Java:如何从数据库创建动态JSON树?

时间:2019-09-19 03:19:15

标签: java json database tree

我在数据库中有一个表,其结构和数据如下:

enter image description here

我想通过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":[

                ]
             }
          ]
       },
       ...
    ]

有人可以帮我吗?

谢谢。:)

1 个答案:

答案 0 :(得分:2)

按照下面的步骤进行操作

  1. 为结果创建一个类
public class NodeBean implements Serializable {
     private static final long serialVersionUID = 1L;
     private Integer id;
     private String text;
     private List children;
}
  1. 从DB创建数据映射类
public class NodeInfoBean {
     private Integer id;
     private String text; 
}
  1. 写一个方法来通过parentId从数据库获取数据:
 private List<NodeInfoBean> getData(Integer parentId) {

      // select id, text from table where parent_id = :parentId
 }
  1. 写一种构建数据的方法:
 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;
}
  1. 主要,调用此方法以获取结果:
 List<NodeBean> data = buildNode(null);
 return new ObjectMapper().writeValueAsString(data);
  1. 查看结果:
  [{
       "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": []
             }
           ]
         }
]}]