当前位置:编程学习 > JS >>

递归循环JSON

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
  
/// <summary>  
/// JsonHelper 的摘要说明  
/// </summary>  
public class JsonHelper  
{  
    /// <summary>  
    /// 转换JSON对象  
    /// </summary>  
    /// <param name="company"></param>  
    /// <returns></returns>  
    public static string ConvertToJson(Company company)  
    {  
        string json = "CompanyName:\"" + company.CompanyName + "\",ContactName:\"" + company.ContactName + "\",City:\"" + company.City + "\",CustomerID:\"" + company.CustomerID + "\",children:{0}";  
        return json;  
    }  
  
    /// <summary>  
    /// 转换JSON对象集合,包含子集,递归加载  
    /// </summary>  
    /// <param name="companyList"></param>  
    /// <returns></returns>  
    public static string ConvertToJson(List<Company> companyList)  
    {  
        string json = "[";  
        //获取第一级目录  
        List<Company> rootList = companyList.Where(x => string.IsNullOrEmpty(x.Pid)).ToList<Company>();  
        foreach (Company root in rootList)  
        {  
            string js = ConvertToJson(root);  
            string children="";  
            children = DiGui(companyList, children, root.CustomerID);  
            json += "{"+string.Format(js, children) + "},";  
        }  
        if (json.LastIndexOf(",") < 1)  
        {  
            json += "]";  
        }  
        else  
        {  
            json = json.Substring(0, json.Length - 1) + "]";  
        }  
        return json.Replace(",children:[]", "");  
    }  
  
    /// <summary>  
    /// 递归调用添加包含子集的JSON数组  
    /// </summary>  
    private static string DiGui(List<Company> companyList,string children,string pid)  
    {  
        children = "[";  
        List<Company> childerList = companyList.Where(x => x.Pid.ToUpper() == pid.ToUpper()).ToList<Company>();  
        foreach (Company item in childerList)  
        {  
            string js = ConvertToJson(item);  
            string cd = "";  
            cd = DiGui(companyList, cd, item.CustomerID);  
            children += "{"+string.Format(js, cd) + "},";  
        }  
        if (children.LastIndexOf(",") < 1)  
        {  
            children += "]";  
        }  
        else  
        {  
            children = children.Substring(0, children.Length - 1) + "]";  
        }  
        return children;  
    }  
  
      
  
}  

 

补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,