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;
} }

最新文章

  1. Js计算当前日,当前周开始结束时间,当前月份,当前年份
  2. MVC架构学习之Smarty学习——病来而蔫
  3. 【SPOJ QTREE2】QTREE2 - Query on a tree II(LCA)
  4. &lt;转&gt;Npoi导入导出Excel操作&lt;载&gt;
  5. 五、mysql存储引擎
  6. C++实现一个单例模板类
  7. 纯CSS无hacks的跨游览器多列布局
  8. C++中文件的操作
  9. lua调用C语言
  10. BZOJ2002(分块)
  11. LeetCode 16. 3Sum Closest. (最接近的三数之和)
  12. python 多进程/多线程/协程 同步异步
  13. ESP8266 NOOS SDK libat.a Functions
  14. kindle看扫描版pdf的解决办法
  15. .NET 除了用 Task 之外,如何自己写一个可以 await 的对象?
  16. K-SVD字典学习及其实现(Python)
  17. 使用xml4j xml与字符串之间转换
  18. Java之自动拆装箱
  19. SQL SERVER -&gt;&gt; IDENTITY相关函数
  20. ohasd failed to start: Inappropriate ioctl for device

热门文章

  1. poj 3087 Shuffle&#39;m Up ( map 模拟 )
  2. struts2的action中获得request response session 对象
  3. bzoj1001
  4. Java内省
  5. Dubbo实例
  6. 在Azure HDInsight HBase集群中使用Thrift接口
  7. hdu 1712 ACboy needs your help
  8. Asp.net MVC 4 异步方法
  9. InnoDB关键特性之doublewrite
  10. mac usb转串口 连接树莓PI