Fork me on GitHub

GetJsonByDataTable

        public string getJsonByModel(DataTable dt)
        {
            StringBuilder nsb = new StringBuilder();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("{");
                foreach (DataColumn mDc in dt.Columns)
                {
                    if (dt.Rows[i][mDc] != null)
                    {
                        var cname = mDc.ColumnName;
                        var cvalue = "";
                        cvalue = dt.Rows[i][mDc].ToString();
                        sb.Append("\"" + cname + "\":").Append("\"" + Microsoft.JScript.GlobalObject.escape(cvalue) + "\",");
                    }
                    else
                    {
                        sb.Append("\"" + mDc.ColumnName + "\":").Append("\"\",");
                    }
                }
                var ss = sb.ToString();
                ss = ss.Remove(ss.LastIndexOf(","), 1);
                ss += "}";
                nsb.Append(ss);
                if (i < dt.Rows.Count - 1)
                {
                    nsb.Append(",");
                }
            }
            return nsb.ToString();
        }

 

posted @ 2015-06-23 08:29  乔闻  阅读(251)  评论(0编辑  收藏  举报