using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetJSON();
}
public DataTable GetDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("sex");
dt.Columns.Add("age");
dt.Columns.Add ("discription");
DataRow dr = dt.NewRow();
dr["id"] = 1;
dr["name"] = "赵红叶";
dr["sex"] = "女";
dr["age"] = "20";
dr["discription"] = "红福爱人";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = 2;
dr["name"] = "李明莉";
dr["sex"] = "女";
dr["age"] = "20";
dr["discription"] = "红福的好朋友";
dt.Rows.Add(dr);
return dt;
}
public 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();
}
public void GetJSON()
{
if (Request.QueryString["name"] != null)
{
Response.Clear();
Response.ContentType = "text/plain";
string json = DataTableToJson("friend", GetDataTable());
Response.Write(json);
Response.End();
}
}
}
}