Easyui tree reads SQL Server table structure to get JSON format

Source: Internet
Author: User
Tags serialization

Originally the project needs a tree structure, and then randomly chose a easyui tree open source Framework, and then encountered a problem, I want to recursively from the database structure, turn to JSON, how to do? Is it a recursive stitching StringBuilder? It would be foolish to do so. Then all kinds of Baidu, blog Park, QQ Group to ask, the answer is also a variety of, no one to give me detailed, I had to figure it out.

First: The table of the recursive database.

Second: Serialize the final recursive result.

Here is the table for my database:

                    

Then the following is the code:

There is a need to create an entity class, the property of the class is the same as the database table, just a generic attribute, is to save the sub-object, you want to see, if the properties of this class are: Id,name,parentid (database field) How do you recursively get father-son relationship tree? So just one more field, this field is generic, for example, the class I declare below is called Tree, so there are 4 properties in my class: Id,name,parentid,item, because in Easyui tree, its JSON structure is this:

[{"id": "1", "Text": "Folder", "status": "Open", "children":

[{"id": "1", "Text": "Folder", "status": "Open", "Children": null}]

}]

So much of this list<tree> is to keep an identical sub-object, where I declare item to hold the child object.

 1  public  class   Tree  2   { 3  public  int   ID;  4  public  string   Name;  5  public  int   ParentID;  6  public  list<tree> item;  7 } 

Here is the recursive method I wrote:

1      /// <summary>2         ///The tree structure that is used to traverse the database table to hold the hierarchy relationship3         /// </summary>4         /// <param name= "ParentID" >Parent ID</param>5         /// <param name= "Li" >List Object</param>6         /// <returns></returns>7         protectedList<tree> Recursive (intParentid,list<tree>Li)8         {9DataSet ds_content = Sql.getdata ("SELECT * from tb_cm WHERE parentid="+parentid);Ten             if(Ds_content. tables[0]. Rows.Count >0)//judge if the result of the query is not empty, go to recursion One             {            A                 //DataSet ds_content = Sql.getdata ("select * from tb_cm WHERE parentid=" + parentid);//query based on parent ID has no child ID -                  for(inti =0; I < Ds_content. tables[0]. Rows.Count; i++) -                 { thelist<tree> lis =NewList<tree> ();//declares a generic to hold sub-objects, the tree is a class that I have built myself, -Tree T =NewTree (); -T.id =int. Parse (ds_content. tables[0]. rows[i][0].               ToString ());  -T.name = ds_content. tables[0]. rows[i][1].                        ToString ();  +T.parentid=int. Parse (ds_content. tables[0]. rows[i][2].         ToString ());  -DataSet Ds_haveitem = Sql.getdata ("SELECT ID from tb_cm WHERE parentid="+t.id);//queries are used to determine if there are child objects +                     //ternary operator judgment greater than 0 means there are child objects, there is a return traversal, otherwise return null AT.item = ds_haveitem.tables[0]. Rows.Count >0? Recursive (T.id, Lis):NULL; at  - Li.                        ADD (t);  -                 } -             } -             returnLi; -}

This is serialization, and serialization becomes JSON format, so you do not need to Sb.append ("[{") such a concatenation string:

1  protected voidPage_Load (Objectsender, EventArgs e)2         {3Gridview1.datasource = Sql.getdata ("SELECT * from tb_cm");4 Gridview1.databind ();5 6List<tree> Li =NewList<tree>();7Response.Write (Newtonsoft.Json.JsonConvert.SerializeObject (Recursive (0, Li));8}

This Newtonsoft.Json.JsonConvert.SerializeObject () serialization is what I said when I went to csdn to see someone else's answer, this is something that someone else encapsulated, downloaded from GitHub, downloaded and put in the project, Click "Add Reference" in the project, then select "Browse" to find the DLL in your project, and then this is the case:

The following SQL is my own set of classes, which return query results, you can write it yourself, remember in this class, the most referenced place input: using System.Configuration;

1      Public classSQL2     {3         Static stringConnStr = configurationmanager.connectionstrings["ConnStr"]. ToString ();4 5         StaticSqlConnection conn =NewSqlConnection (CONNSTR);6 7          Public StaticDataSet GetDaTa (stringsql)8         {9DataSet ds =NewDataSet ();TenSqlDataAdapter SDA =NewSqlDataAdapter (SQL, conn); One SDA. Fill (DS); A              -             returnds; -         } the  -}

Configuration file:

Then run it:

The JSON format has been output, and it is assigned to the JSON online editor to see how?

Well, everything is normal, I do not do the front desk, you use your own in front of the AJAX request to return to the background of the results on the line. Sleep, and then go to work.

Easyui tree reads SQL Server table structure to get JSON format

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.