using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write(DataTableToJson(MyTable()));
Console.Read();
}
//"{\"totalpage\":\"10\",\"data\":[\"pic1\",\"pic2\",\"pic\"]}"
// {totalpage:10,data:[pic1,pic2,pic]}
public static string DataTableToJson(DataTable dt)
{
string columnFirst = "";
List<string> result=new List<string>();
StringBuilder Json = new StringBuilder();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (columnFirst != dt.Rows[i][0].ToString())
{
if (i != 0)
{
AddNewJson(Json, result, dt);
}
columnFirst = dt.Rows[i][0].ToString();
result = new List<string>();
for (int k = 0; k < dt.Columns.Count; k++)
{
result.Add("\"" + dt.Rows[i][k].ToString() + "\"");
}
}
else
{
for (int k = 0; k < dt.Columns.Count; k++)
{
if (!result[k].Contains(dt.Rows[i][k].ToString()))
{
result[k] += ",\"" + dt.Rows[i][k].ToString()+"\"";
}
}
}
if (i == dt.Rows.Count - 1)
{
AddNewJson(Json, result, dt);
}
}
}
return Json.ToString();
}
private static void AddNewJson(StringBuilder Json,List<string> result,DataTable dt)
{
Json.Append("{");
for (int i = 0; i < dt.Columns.Count;i++ )
{
Json.Append("\"");
Json.Append(dt.Columns[i].ColumnName);
Json.Append("\":");
if (result[i].Contains(","))
{
Json.Append("[");
Json.Append(result[i]);
if (i == dt.Columns.Count - 1)
{
Json.Append("]");
}
else
{
Json.Append("],");
}
}
else
{
Json.Append(result[i]);
if (i != dt.Columns.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("}");
}
private static DataTable MyTable()
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
dc.ColumnName = "ID";
dc.DataType = typeof(String);
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "Name";
dc.DataType = typeof(String);
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "Score";
dc.DataType = typeof(String);
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["ID"] = "01";
dr["Name"] = "Jin";
dr["Score"] = "10";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "01";
dr["Name"] = "Xin";
dr["Score"] = "20";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "01";
dr["Name"] = "Xu";
dr["Score"] = "30";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "02";
dr["Name"] = "Xin";
dr["Score"] = "30";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "02";
dr["Name"] = "Jin";
dr["Score"] = "30";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "02";
dr["Name"] = "Jin";
dr["Score"] = "30";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "02";
dr["Name"] = "Jin";
dr["Score"] = "40";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "02";
dr["Name"] = "Jin";
dr["Score"] = "30";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "02";
dr["Name"] = "Jin";
dr["Score"] = "30";
dt.Rows.Add(dr);
return dt;
}
}
}