• .Net :DataTable + List to Json


    //DataTable转成Json
            public static string DataTableToJson(string jsonName, DataTable dt)
            {
                StringBuilder Json = new StringBuilder();
                Json.Append("{\"" + jsonName + "\":[");
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Json.Append("{");
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
                            if (j < dt.Columns.Count - 1)
                            {
                                Json.Append(",");
                            }
                        }
                        Json.Append("}");
                        if (i < dt.Rows.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                }
                Json.Append("]}");
                return Json.ToString();
            }

            //List转成json
            public static string ObjectToJson<T>(string jsonName, IList<T> IL)
            {
                StringBuilder Json = new StringBuilder();
                Json.Append("{\"" + jsonName + "\":[");
                if (IL.Count > 0)
                {
                    for (int i = 0; i < IL.Count; i++)
                    {
                        T obj = Activator.CreateInstance<T>();
                        Type type = obj.GetType();
                        PropertyInfo[] pis = type.GetProperties();
                        Json.Append("{");
                        for (int j = 0; j < pis.Length; j++)
                        {
                            Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
                            if (j < pis.Length - 1)
                            {
                                Json.Append(",");
                            }
                        }
                        Json.Append("}");
                        if (i < IL.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                }
                Json.Append("]}");
                return Json.ToString();
            }

  • 相关阅读:
    POJ 2352 &amp;&amp; HDU 1541 Stars (树状数组)
    SSH三大框架的工作原理及流程
    稀疏表示
    Linux程序设计学习笔记----多线程编程线程同步机制之相互排斥量(锁)与读写锁
    [面经] 南京SAP面试(上)
    JAVA数组的定义及用法
    花指令
    计算机认证考试种类
    《C语言编写 学生成绩管理系统》
    spice for openstack
  • 原文地址:https://www.cnblogs.com/Fooo/p/1992035.html
Copyright © 2020-2023  润新知