(转)Asp.Net 使用“递归算法”生成目录树的JSON格式(值得收藏)
以下博文转自:http://www.cnblogs.com/yangrixing/archive/2012/08/23/2651900.html
今天在群里有群友求助,吾正好有空,顺便解答一下。
废话少说中,直切主题。
主要解决内容:将一个数据表生成一个JSON格式的,有层次结构的“目录”树。
生成的JSON字符串经过格式化后,如下图所示:
图1 效果图
如何实现呢?
一、给出数据库的结构,让大家思考一下。
数据库的结构和数据截图分别如下:
图2 数据库结构 图3 数据库中的数据
好了,数据库的结构已经给出了,那,应该如何生成像图1所示的JSON数据格式呢?
毫无疑问,必须用到“序列化”吧?
毫无疑问,必须用到“递归算法”吧?如果您不知道的除外~我的博客里有收集了一些“递归算法”的经典应用,欢迎移步。
嗯,没错。那就让我们来看看如何设计这个递归算法了。
第一步:根所JSON格式,先写相应的实体类,为读取数据后封装提供支持。
先来分析一下JSON数据的结构,终合而言,是由一个text字段,children[]数据组成的对象(我们且称之为item对象吧),而children[]数组中,又包含了该对象。因为,可以利用此特性,设计一个类以支持递归算法的实现。
废话少说了,直接贴码了:
代码1 封装好的类,如下图所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// 节点的实体类,记录了数据库中的3个字段
/// 为的是方便操作
/// </summary>
[Serializable]
public class Items
{
public int bh;
public string text;
public int parentBh;
}
/// <summary>
/// 节点类,基础类
/// </summary>
[Serializable]
public class JieDian
{
public string text= "";
public jieDian[] children = null;
}
[Serializable]
public class Cliet
{
// 根据parentBh获取相应的子目录集合
public Items[] GetTheItems ( string parentBh)
{
// 根据父节点获取选项集合
string sql = " select * from Table_3 where parentBh= " +parentBh; // 这里改成你的数据库表
SqlDataReader dr = SQLHelp.ExecuteReader(sql); // 这里我直接调用了我库中的类
List<Items> items = new System.Collections.Generic.List<Items>();
while (dr.Read())
{
Items i = new items();
i.bh = dr.GetInt32( 0);
i.text = dr.GetString( 1);
i.parentBh = dr.GetInt32( 2);
items.Add(i);
}
dr.Close(); // 一定要对这进行关闭
return items.ToArray(); // 返回
}
// 生成树的方法
public void creatTheTree ( string parentBh ,jieDian jd)
{
// 获取
Items[] items = GetTheItems(parentBh);
if (items.Length == 0)
return; // 如果没有字节点了,那就返回空
List<JieDian> jdList = new System.Collections.Generic.List<JieDian>();
for ( int i = 0; i < items.Length; i++)
{
JieDian jiedian = new JieDian();
jiedian.text = items[i].text;
creatTheTree(items[i].bh.ToString(), jiedian);
jdList.Add(jiedian);
}
jd.children = jdList.ToArray(); // 由于对象是引用类型,因为可以改变参数的值
}
}
第二步:调用写好的类,序列化成JSON格式
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// 节点的实体类,记录了数据库中的3个字段
/// 为的是方便操作
/// </summary>
[Serializable]
public class Items
{
public int bh;
public string text;
public int parentBh;
}
/// <summary>
/// 节点类,基础类
/// </summary>
[Serializable]
public class JieDian
{
public string text= "";
public jieDian[] children = null;
}
[Serializable]
public class Cliet
{
// 根据parentBh获取相应的子目录集合
public Items[] GetTheItems ( string parentBh)
{
// 根据父节点获取选项集合
string sql = " select * from Table_3 where parentBh= " +parentBh; // 这里改成你的数据库表
SqlDataReader dr = SQLHelp.ExecuteReader(sql); // 这里我直接调用了我库中的类
List<Items> items = new System.Collections.Generic.List<Items>();
while (dr.Read())
{
Items i = new items();
i.bh = dr.GetInt32( 0);
i.text = dr.GetString( 1);
i.parentBh = dr.GetInt32( 2);
items.Add(i);
}
dr.Close(); // 一定要对这进行关闭
return items.ToArray(); // 返回
}
// 生成树的方法
public void creatTheTree ( string parentBh ,jieDian jd)
{
// 获取
Items[] items = GetTheItems(parentBh);
if (items.Length == 0)
return; // 如果没有字节点了,那就返回空
List<JieDian> jdList = new System.Collections.Generic.List<JieDian>();
for ( int i = 0; i < items.Length; i++)
{
JieDian jiedian = new JieDian();
jiedian.text = items[i].text;
creatTheTree(items[i].bh.ToString(), jiedian);
jdList.Add(jiedian);
}
jd.children = jdList.ToArray(); // 由于对象是引用类型,因为可以改变参数的值
}
}
新建一个“一般处理程序(.ashx),直接用C#的一般处理程序生成,以便前台通过异步接收到生成的字符串。
代码如下所示:

<%@ WebHandler Language=
"
C#
" Class=
"
Handler
" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using Dkl.New3.Chart;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = " text/plain ";
Cliet clite = new Cliet();
JieDian root = new JieDian();
root.text = " 根节点 ";
clite.creatTheTree( " 0 ", root); // 根节点的parentBh值为"0"
// 对root对象进行序列化
DataContractJsonSerializer dc = new DataContractJsonSerializer(root.GetType());
MemoryStream ms = new MemoryStream();
dc.WriteObject(ms, root);
byte[] aryByte = ms.ToArray();
string json = Encoding.UTF8.GetString(aryByte, 0, aryByte.Length);
ms.Close();
context.Response.Write(json.ToString());
}
public bool IsReusable {
get {
return false;
}
}
}
using System;
using System.Web;
using System.Web.SessionState;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using Dkl.New3.Chart;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = " text/plain ";
Cliet clite = new Cliet();
JieDian root = new JieDian();
root.text = " 根节点 ";
clite.creatTheTree( " 0 ", root); // 根节点的parentBh值为"0"
// 对root对象进行序列化
DataContractJsonSerializer dc = new DataContractJsonSerializer(root.GetType());
MemoryStream ms = new MemoryStream();
dc.WriteObject(ms, root);
byte[] aryByte = ms.ToArray();
string json = Encoding.UTF8.GetString(aryByte, 0, aryByte.Length);
ms.Close();
context.Response.Write(json.ToString());
}
public bool IsReusable {
get {
return false;
}
}
}
第三步:运行
运行结果如下:
图4 运行结果
经
经JSON数据格式化后,工具地址(http://www.bejson.com/go.html?u=http://www.bejson.com/jsonview2/)
得到以下视图:
图5 格式化
第四步:反思。
主要有以下几点反思
1、程序还有诸多一足,只能是一个Deom,还有很多安全方面、序列化顺序、序列化速度、序列化的名称等可以继续完善。
2、加深了对递归算法的理解。
3、这样的设计是否得当?是不是还有更好的办法?
4、这样的设计,容易扩展吗?
嗯,相信日后会继续慢慢完善的。