Java generates a tree JSON based on the list of data in the database

Source: Internet
Author: User
Tags addchild

This code was also my online search, but unfortunately, the data source to the list, unable to return to the foreground, the list to JSON error, I show the correct code

1.

Package Com.labci.javamail.test;import Java.util.arraylist;import Java.util.collections;import java.util.Iterator;   Import java.util.list;/** * Node class */class Node {/** * node number */public String ID;   /** * Node content */public String text;   /** * Parent Node Number */public String parentid;   /** * child Node list */private children children = new Children (); Sequence traversal, stitching JSON string public string toString () {string result = "{" + "ID: '" + ID + "'" + ", Text: '" + Tex    T + "'";    if (children! = null && children.getsize ()! = 0) {result + = ", children:" + children.tostring ();    } else {result + = ", leaf:true";   } return result + "}"; }//Sibling node horizontal sort public void SortChildren () {if (children! = null && children.getsize ()! = 0) {children.    SortChildren ();   }}//Add child node public void AddChild (node node) {This.children.addChild (node); }public String getId () {return ID;} public void SetId (String id) {this.id = ID;} PUblic String GetText () {return text;} public void SetText (String text) {this.text = text;} Public String Getparentid () {return parentid;} public void Setparentid (String parentid) {this.parentid = ParentID;} Public children GetChildren () {return children;}  public void Setchildren (children children) {This.children = children;}  }

2

  Package Com.labci.javamail.test;import java.util.arraylist;import Java.util.collections;import   Java.util.iterator;import java.util.list;/** * Child List class */public class Children {Private List List = new ArrayList ();   public int GetSize () {return list.size ();   } public void AddChild (node node) {List.add (node);      }//Stitching the child node JSON string public string toString () {string result = "["; for (Iterator it = List.iterator (); It.hasnext ();)     {Result + = ((Node) It.next ()). ToString ();    Result + = ",";    } result = result.substring (0, Result.length ()-1);    Result + = "]";   return result; } public List GetList () {return list;} public void setlist (list list) {this.list = list;}    Child node sort public void SortChildren () {//Sort this layer node//can pass in different comparators according to different sorting properties, here incoming ID comparator collections.sort (list); Sort the next layer of nodes for each node for (Iterator it = List.iterator (); It.hasnext ();)    {(Node) It.next ()). SortChildren (); }   }  }  

3

Package Com.labci.javamail.test;import Java.util.arraylist;import Java.util.hashmap;import java.util.List;public Class Virtualdatagenerator {//Comparison by node number public static List Getvirtualresult () {List dataList = new ARR          Aylist ();          HashMap dataRecord1 = new HashMap ();          Datarecord1.put ("id", "112000");          Datarecord1.put ("text", "Langfang Bank Liberation Road Branch");          Datarecord1.put ("ParentID", "110000");          HashMap dataRecord2 = new HashMap ();          Datarecord2.put ("id", "112200");          Datarecord2.put ("text", "Langfang Bank three street sub-branch");          Datarecord2.put ("ParentID", "112000");          HashMap dataRecord3 = new HashMap ();          Datarecord3.put ("id", "112100");          Datarecord3.put ("text", "Langfang Bank Guangyang Road Sub-branch");          Datarecord3.put ("ParentID", "112000");          HashMap DataRecord4 = new HashMap ();          Datarecord4.put ("id", "113000");          Datarecord4.put ("text", "Langfang Bank Development Zone sub-branch");          Datarecord4.put ("ParentID", "110000"); HashMap DatareCord5 = new HashMap ();          Datarecord5.put ("id", "100000");          Datarecord5.put ("text", "Langfang Bank headquarters");          Datarecord5.put ("ParentID", "" ");          HashMap DataRecord6 = new HashMap ();          Datarecord6.put ("id", "110000");          Datarecord6.put ("text", "Langfang branch");          Datarecord6.put ("ParentID", "100000");          HashMap DataRecord7 = new HashMap ();          Datarecord7.put ("id", "111000");          Datarecord7.put ("text", "Langfang Bank Golden Road Sub-branch");          Datarecord7.put ("ParentID", "110000");          HashMap DataRecord8 = new HashMap ();          Datarecord8.put ("id", "111000");          Datarecord8.put ("text", "Langfang Bank Golden Road Branch Wwwwww");          Datarecord8.put ("ParentID", "100000");          Datalist.add (DATARECORD1);          Datalist.add (DATARECORD2);          Datalist.add (DATARECORD3);          Datalist.add (DATARECORD4);          Datalist.add (DATARECORD5);          Datalist.add (DATARECORD6);          Datalist.add (DATARECORD7);          Datalist.add (DATARECORD8); SyStem.out.println (dataList);      return dataList; }  }

4. Note: List dataList = Virtualdatagenerator.getvirtualresult (); list will be replaced by its own list from the database ha

Package com.labci.javamail.test;  Import java.util.ArrayList;  Import Java.util.Comparator;  Import Java.util.HashMap;  Import Java.util.Iterator;  Import java.util.List;  Import Java.util.Map;  Import Java.util.Set;  Import java.util.Collections; Import com.labci.javamail.test.virtualdatagenerator;/** * Multi-fork Tree class */public class Multipletree {public static void M          Ain (string[] args) {//Read hierarchical data result set list dataList = Virtualdatagenerator.getvirtualresult ();          Node list (hash list, temporary storage node object) HashMap nodeList = new HashMap ();          root node-root = null; Put the result set into a hash table (a hash table will be used to construct the multi-fork Tree) for (Iterator it = Datalist.iterator (); It.hasnext ();)              {Map DataRecord = (map) it.next ();              Node node = new node ();              Node.id = (String) datarecord.get ("id");              Node.text = (String) datarecord.get ("text");              Node.parentid = (String) datarecord.get ("ParentID"); Nodelist.put (node.id, node);          }//constructed unordered multi-fork tree Set entryset = Nodelist.entryset (); for (Iterator it = Entryset.iterator (); It.hasnext ();)              {Node node = (node) ((Map.entry) It.next ()). GetValue ();              if (Node.parentid = = NULL | | node.parentId.equals ("")) {root = node;              } else {(node) nodelist.get (Node.parentid)). AddChild (node);          }//Output JSON string System.out.println (root) of unordered tree menu;          Horizontal sorting of multi-fork Trees root.sortchildren ();          A JSON string System.out.println (root) that outputs an ordered tree menu;            The output of the program is as follows:////Unordered Tree menu (formatted results can be viewed using the JSON Format tool,//e.g. http://jsonviewer.stack.hu/online Viewer):          {//ID: ' 100000 ',//text: ' Langfang Bank headquarters ',//children: [///{          ID: ' 110000 ',//text: ' Langfang branch ',//children: [///{  //     ID: ' 113000 ',//text: ' Langfang Bank Development Zone Sub-branch ',//Leaf:true//},// {//ID: ' 111000 ',//text: ' Langfang Bank Cotai Sub-branch ',//Leaf:true/       /},/////ID: ' 112000 ',//text: ' Langfang Bank Jiefang Road Sub-branch ',// Children: [/////ID: ' 112200 ',//text: ' Langfang Bank three street sub-branch ',/         /leaf:true//},//{//ID: ' 112100 ',//          Text: ' Langfang Bank Guangyang Road Sub-branch ',//Leaf:true//}//]//}  ]//}//]//}//Ordered tree menu (formatted result)://{//ID           : ' 100000 ',//text: ' Langfang Bank headquarters ',//children: [/////ID: ' 110000 ', Text:' Langfang branch ',///children: [//////ID: ' 111000 ',//text: ' Langfang Bank           Jin Guang Dao sub-branch ',//Leaf:true//},//{//ID: ' 112000 ',           Text: ' Langfang Bank Liberation Road Sub-branch ',//children: [/////ID: ' 112100 ',          Text: ' Langfang Bank Guangyang Road Sub-branch ',//Leaf:true//},//{         ID: ' 112200 ',//text: ' Langfang Bank three street sub-branch ',//leaf:true//  }//]//},//{//ID: ' 113000 ',//text:          ' Langfang Bank Development Zone Sub-branch ',//Leaf:true//}//]//}//] }}}/** * Node Comparator */class Nodeidcomparator implements Comparator {//Compare public int c by node number Ompare (Object O1, Object O2) {int j1 = Integer.parseint (((Node) O1). ID);          int j2 = Integer.parseint ((Node) O2). ID);      Return (J1 < J2 1: (J1 = = J2? 0:1));   }  }

Java generates a tree JSON based on the list of data in the database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.