ASP.NET返回Json数据

Schedule.ashx:

<%@ WebHandler Language="C#" Class="Schedule" %>



using System;

using System.Data;

using System.Text;

using System.Web;

using System.Web.Script.Serialization;



public class Schedule : IHttpHandler {

    

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "application/json;charset=utf-8";



        //JavaScriptSerializer serializer = new JavaScriptSerializer();

        DataTable dt = Utilities.GetOffSchedule(402, 221).Tables[0];

        //string jsonStr = serializer.Serialize(list);

        context.Response.Clear();

        string jsonStr = DataTableToJson("list", dt);

        context.Response.Write(jsonStr);

        //context.Response.End();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }



    public static 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();

    }



}

 

你可能感兴趣的:(asp.net)