json格式後臺轉換使用

 ashx.cs中需要的工作:

一般處理程序中使用Session:
如果想要在ashx中應用Session則必須先引入一個頭文件using System.Web.SessionState;
然後
public class JsonHandler : IHttpHandler, IRequiresSessionState/*IRequiresSessionState是新添加的,需要實現這個接口才能使用Session*/
{
public void Proce***equest(HttpContext context)
{
HttpContext.Current.Response.CacheControl = "no-cache";
string name = context.Session["Name"].ToString();  /*注意這裏需要加上context*/
}
 
一般處理程序當中清除瀏覽器緩存:
HttpContext.Current.Response.CacheControl = "no-cache";   /*意思就是把當前響應中的緩存設置爲不緩存,即爲清除緩存!一般是加在最前面*/
 
將DataSet類型的數據轉化爲JSON格式的數據:
public static string ToJson(DataTable dt)  //將DataSet類型的數據轉化爲JSON格式的數據
{
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");        
            return jsonBuilder.ToString();
}  
 public static string ToJson(DataSet ds)
{
       StringBuilder json = new StringBuilder();
       foreach (DataTable dt in ds.Tables)
       {
                json.Append("{\"");
                json.Append(dt.TableName);
                json.Append("\":");
                json.Append(ToJson(dt));
                json.Append("}");
       }
       return json.ToString();
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章