using System;using System.Collections.Generic;using System.Linq;using System.Web;/// /// JsonHelper 的摘要说明/// public class JsonHelper{ /// /// 转换JSON对象 /// /// /// public static string ConvertToJson(Company company) { string json = "CompanyName:\"" + company.CompanyName + "\",ContactName:\"" + company.ContactName + "\",City:\"" + company.City + "\",CustomerID:\"" + company.CustomerID + "\",children:{0}"; return json; } /// /// 转换JSON对象集合,包含子集,递归加载 /// /// /// public static string ConvertToJson(List companyList) { string json = "["; //获取第一级目录 List rootList = companyList.Where(x => string.IsNullOrEmpty(x.Pid)).ToList (); 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:[]", ""); } /// /// 递归调用添加包含子集的JSON数组 /// private static string DiGui(List companyList,string children,string pid) { children = "["; List childerList = companyList.Where(x => x.Pid.ToUpper() == pid.ToUpper()).ToList (); 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; } }