递归循环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;
    }

    

}


posted on 2013-10-15 09:03  新一  阅读(548)  评论(0编辑  收藏  举报

导航