json 绑定

http://www.csaspx.com/articlelist-952.html

 

///
    /// 根据DataTable生成Json树结构
    ///
    ///数据源
    ///ID列
    ///Text列
    ///关系字段
    ///父ID
    StringBuilder result = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    private void GetTreeJsonByTable(DataTable tabel,string idCol, string txtCol, string rela, object pId)
    {
       result.Append(sb.ToString());
        sb.Clear();
        if (tabel.Rows.Count >0)
        {
           sb.Append("[");
           string filer = string.Format("{0}=‘{1}‘", rela, pId);
           DataRow[] rows = tabel.Select(filer);
           if (rows.Length > 0)
           {
               foreach (DataRow row in rows)
               {
                   sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" +row[txtCol] + "\",\"state\":\"open\"");
                   if (tabel.Select(string.Format("{0}=‘{1}‘", rela,row[idCol])).Length > 0)
                   {
                       sb.Append(",\"children\":");
                       GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
                       result.Append(sb.ToString());
                       sb.Clear();
                   }
                   result.Append(sb.ToString());
                   sb.Clear();
                   sb.Append("},");
               }
               sb = sb.Remove(sb.Length - 1, 1);
           }
           sb.Append("]");
           result.Append(sb.ToString());
           sb.Clear();
        }
    }

 

调用方法很简单,运行这个void 类型的函数,然后取result 的值就行了,

GetTreeJsonByTable(datatable, "id", "title", "pid", "0");
string content = result.ToString();

干货啊 。好东西啊 。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。