把一个DataTable转换成JSON

abstract class JSONConverter
    {
        public JSONConverter()
        { }

        static public string GetJSONData(DataTable dtable)
        {
            StringBuilder JsonBuilder = new StringBuilder();
            StringBuilder content = new StringBuilder();

            foreach (DataRow dr in dtable.Rows)
            {
                content.Append("{").Append(GetRowData(dr)).Append("}, ");
            }

            if (content.Length > 0)
            {
                JsonBuilder.Append("{").AppendFormat("\"{0}\": ", dtable.TableName);

                if (content.ToString().Trim().EndsWith(","))
                {
                    JsonBuilder.AppendFormat("[ {0} ]", content.ToString().Substring(0, content.Length - 2)).Append("}");
                }
                else
                {
                    JsonBuilder.AppendFormat("[ {0} ]", content.ToString()).Append("}");
                }
            }
            return JsonBuilder.ToString();
        }

      static private string GetRowData(DataRow dr)
        {
            string sData = "";
            foreach (DataColumn col in dr.Table.Columns)
            {
                float val = 0;
                if ( float.TryParse(dr[col.ColumnName].ToString(), out val))
                {
                    sData = sData + "\"" + col.ColumnName + "\"" + ":" + val + ",";
                }
                else
                {
                    sData = sData + "\"" + col.ColumnName + "\"" + ":\"" + dr[col.ColumnName] + "\",";
                }
            }

            if (sData.EndsWith(","))
                sData = sData.Substring(0, sData.Length - 1);

            return sData;
        }

    }

 

 

 

 

posted on 2012-07-15 21:34  gzh4455  阅读(417)  评论(0编辑  收藏  举报