Datatable 生成json格式


public string GetJsonFromDataTable(DataTable dt, int total, bool ShowFooter, string fields, string inputfiled, string ShowMessage = "合计:", string filter = "")
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (dt.Rows.Count == 0)
			{
				stringBuilder.Append("{ ");
				stringBuilder.Append("\"rows\":[ ");
				stringBuilder.Append("]");
				stringBuilder.Append(",");
				stringBuilder.Append("\"total\":");
				stringBuilder.Append(total);
				stringBuilder.Append(",\"footer\":[");
				stringBuilder.Append("]");
				stringBuilder.Append("}");
				return stringBuilder.ToString();
			}
			stringBuilder.Append("{ ");
			stringBuilder.Append("\"rows\":[ ");
			for (int i = 0; i < dt.Rows.Count; i++)
			{
				stringBuilder.Append("{ ");
				for (int j = 0; j < dt.Columns.Count; j++)
				{
					if (j < dt.Columns.Count - 1)
					{
						stringBuilder.Append(string.Concat(new string[]
						{
							"\"",
							dt.Columns[j].ColumnName.ToString().ToLower(),
							"\":\"",
							this.JsonCharFilter(dt.Rows[i][j].ToString()),
							"\","
						}));
					}
					else
					{
						if (j == dt.Columns.Count - 1)
						{
							stringBuilder.Append(string.Concat(new string[]
							{
								"\"",
								dt.Columns[j].ColumnName.ToString().ToLower(),
								"\":\"",
								this.JsonCharFilter(dt.Rows[i][j].ToString()),
								"\""
							}));
						}
					}
				}
				if (i == dt.Rows.Count - 1)
				{
					stringBuilder.Append("} ");
				}
				else
				{
					stringBuilder.Append("}, ");
				}
			}
			stringBuilder.Append("]");
			stringBuilder.Append(",");
			stringBuilder.Append("\"total\":");
			stringBuilder.Append(total);
			if (ShowFooter && fields.Length > 0 && inputfiled.Length > 0)
			{
				stringBuilder.Append(",\"footer\":[{");
				stringBuilder.Append(string.Concat(new string[]
				{
					"\"",
					inputfiled,
					"\":\"<span style='color:red;  font-weight:bold'>",
					ShowMessage,
					"</span>\","
				}));
				string[] array = fields.Split(new char[]
				{
					','
				});
				for (int k = 0; k < array.Length; k++)
				{
					if (k < array.Length - 1)
					{
						stringBuilder.Append(string.Concat(new object[]
						{
							"\"",
							array[k],
							"\":\"",
							dt.Compute("sum(" + array[k] + ")", filter),
							"\","
						}));
					}
					else
					{
						stringBuilder.Append(string.Concat(new object[]
						{
							"\"",
							array[k],
							"\":\"",
							dt.Compute("sum(" + array[k] + ")", filter),
							"\""
						}));
					}
				}
				stringBuilder.Append("}]");
			}
			stringBuilder.Append("}");
			return stringBuilder.ToString();
		}

  

posted @ 2014-05-09 12:13  放哨De老鼠  阅读(272)  评论(0编辑  收藏  举报