1. 程式人生 > >把dataset資料轉換成json的格式通用方法

把dataset資料轉換成json的格式通用方法


/// <summary>
        /// 把dataset資料轉換成json的格式
        /// </summary>
        /// <param name="ds">dataset資料集</param>
        /// <returns>json格式的字串</returns>
        public static string GetJsonByDataset(DataSet ds)
        {
            if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
            {
                //如果查詢到的資料為空則返回標記ok:false
                return "{\"ok\":false}";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"ok\":true,");
            foreach (DataTable dt in ds.Tables)
            {
                sb.Append(string.Format("\"{0}\":[",dt.TableName));

                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("{");
                    for (int i = 0; i < dr.Table.Columns.Count; i++)
                    {
                        sb.AppendFormat("\"{0}\":\"{1}\",", dr.Table.Columns[i].ColumnName.Replace("\"", "\\\"").Replace("\'", "\\\'"), ObjToStr(dr[i]).Replace("\"", "\\\"").Replace("\'", "\\\'")).Replace(Convert.ToString((char)13), "\\r\\n").Replace(Convert.ToString((char)10), "\\r\\n");
                    }
                    sb.Remove(sb.ToString().LastIndexOf(','), 1);
                    sb.Append("},");
                }

                sb.Remove(sb.ToString().LastIndexOf(','), 1);
                sb.Append("],");
            }
            sb.Remove(sb.ToString().LastIndexOf(','), 1);
            sb.Append("}");
            return sb.ToString();
        }

        /// <summary>
        /// 將object轉換成為string
        /// </summary>
        /// <param name="ob">obj物件</param>
        /// <returns></returns>
        public static string ObjToStr(object ob)
        {
            if (ob == null)
            {
                return string.Empty;
            }
            else
                return ob.ToString();
        }相應的jQuery讀取json方式


複製程式碼
 $.getJSON("page.aspx",{process:'getinfo',idx:idx},function(json){
            if(json.ok==true){
                $("#slGameType").val(json.Table[0].GameType);
                $("#txtSelectName").val(json.Table[0].SelectName);
                $("#txtmyName").val(json.Table1[0].myName);
                 $("#txtmyinfo").val(json.Table1[0].info);
           }
        });
複製程式碼
 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;   
using System.Text;   
using System.Text.RegularExpressions;

/// <summary>
/// Creat_Json 任意型別資料轉成JSON格式資料輸出
/// </summary>
public class Creat_Json
{
public Creat_Json()
{
   //
   // TODO: 在此處新增建構函式邏輯
   //
}
    /// <summary>   
    /// List轉成json    
    /// </summary>   
    /// <typeparam name="T"></typeparam>   
    /// <param name="jsonName"></param>   
    /// <param name="list"></param>   
    /// <returns></returns>   
    public static string ListToJson<T>(IList<T> list, string jsonName)
    {
        StringBuilder Json = new StringBuilder();
        if (string.IsNullOrEmpty(jsonName))
            jsonName = list[0].GetType().Name;
        Json.Append("{\"" + jsonName + "\":[");
        if (list.Count > 0)
        {
            for (int i = 0; i < list.Count; i++)
            {
                T obj = Activator.CreateInstance<T>();
                PropertyInfo[] pi = obj.GetType().GetProperties();
                Json.Append("{");
                for (int j = 0; j < pi.Length; j++)
                {
                    Type type = pi[j].GetValue(list[i], null).GetType();
                    Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                    if (j < pi.Length - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < list.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]}");
        return Json.ToString();
    }

    /// <summary>   
    /// List轉成json    
    /// </summary>   
    /// <typeparam name="T"></typeparam>   
    /// <param name="list"></param>   
    /// <returns></returns>   
    public static string ListToJson<T>(IList<T> list)
    {
        object obj = list[0];
        return ListToJson<T>(list, obj.GetType().Name);
    }

    /// <summary>    
    /// 物件轉換為Json字串    
    /// </summary>    
    /// <param name="jsonObject">物件</param>    
    /// <returns>Json字串</returns>    
    public static string ToJson(object jsonObject)
    {
        string jsonString = "{";
        PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
        for (int i = 0; i < propertyInfo.Length; i++)
        {
            object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
            string value = string.Empty;
            if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
            {
                value = "'" + objectValue.ToString() + "'";
            }
            else if (objectValue is string)
            {
                value = "'" + ToJson(objectValue.ToString()) + "'";
            }
            else if (objectValue is IEnumerable)
            {
                value = ToJson((IEnumerable)objectValue);
            }
            else
            {
                value = ToJson(objectValue.ToString());
            }
            jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
        }
        jsonString.Remove(jsonString.Length - 1, jsonString.Length);
        return jsonString + "}";
    }

    /// <summary>    
    /// 物件集合轉換Json    
    /// </summary>    
    /// <param name="array">集合物件</param>    
    /// <returns>Json字串</returns>    
    public static string ToJson(IEnumerable array)
    {
        string jsonString = "[";
        foreach (object item in array)
        {
            jsonString += ToJson(item) + ",";
        }
        jsonString.Remove(jsonString.Length - 1, jsonString.Length);
        return jsonString + "]";
    }

    /// <summary>    
    /// 普通集合轉換Json    
    /// </summary>    
    /// <param name="array">集合物件</param>    
    /// <returns>Json字串</returns>    
    public static string ToArrayString(IEnumerable array)
    {
        string jsonString = "[";
        foreach (object item in array)
        {
            jsonString = ToJson(item.ToString()) + ",";
        }
        jsonString.Remove(jsonString.Length - 1, jsonString.Length);
        return jsonString + "]";
    }

    /// <summary>    
    /// Datatable轉換為Json    
    /// </summary>    
    /// <param name="table">Datatable物件</param>    
    /// <returns>Json字串</returns>    
    public static string ToJson(DataTable dt)
    {
        StringBuilder jsonString = new StringBuilder();
        jsonString.Append("[");
        DataRowCollection drc = dt.Rows;
        for (int i = 0; i < drc.Count; i++)
        {
            jsonString.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                string strKey = dt.Columns[j].ColumnName;
                string strValue = drc[i][j].ToString();
                Type type = dt.Columns[j].DataType;
                jsonString.Append("\"" + strKey + "\":");
                strValue = StringFormat(strValue, type);
                if (j < dt.Columns.Count - 1)
                {
                    jsonString.Append(strValue + ",");
                }
                else
                {
                    jsonString.Append(strValue);
                }
            }
            jsonString.Append("},");
        }
        jsonString.Remove(jsonString.Length - 1, 1);
        jsonString.Append("]");
        return jsonString.ToString();
    }

    /// <summary>   
    /// DataTable轉成Json    
    /// </summary>   
    /// <param name="jsonName"></param>   
    /// <param name="dt"></param>   
    /// <returns></returns>   
    public static string ToJson(DataTable dt, string jsonName)
    {
        StringBuilder Json = new StringBuilder();
        if (string.IsNullOrEmpty(jsonName))
            jsonName = dt.TableName;
        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++)
                {
                    Type type = dt.Rows[i][j].GetType();
                    Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
                    if (j < dt.Columns.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < dt.Rows.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]}");
        return Json.ToString();
    }

    /// <summary>    
    /// DataReader轉換為Json    
    /// </summary>    
    /// <param name="dataReader">DataReader物件</param>    
    /// <returns>Json字串</returns>    
    public static string ToJson(DbDataReader dataReader)
    {
        StringBuilder jsonString = new StringBuilder();
        jsonString.Append("[");
        while (dataReader.Read())
        {
            jsonString.Append("{");
            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                Type type = dataReader.GetFieldType(i);
                string strKey = dataReader.GetName(i);
                string strValue = dataReader[i].ToString();
                jsonString.Append("\"" + strKey + "\":");
                strValue = StringFormat(strValue, type);
                if (i < dataReader.FieldCount - 1)
                {
                    jsonString.Append(strValue + ",");
                }
                else
                {
                    jsonString.Append(strValue);
                }
            }
            jsonString.Append("},");
        }
        dataReader.Close();
        jsonString.Remove(jsonString.Length - 1, 1);
        jsonString.Append("]");
        return jsonString.ToString();
    }

    /// <summary>    
    /// DataSet轉換為Json    
    /// </summary>    
    /// <param name="dataSet">DataSet物件</param>    
    /// <returns>Json字串</returns>    
    public static string ToJson(DataSet dataSet)
    {
        string jsonString = "{";
        foreach (DataTable table in dataSet.Tables)
        {
            jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
        }
        jsonString = jsonString.TrimEnd(',');
        return jsonString + "}";
    }

    /// <summary>   
    /// 過濾特殊字元   
    /// </summary>   
    /// <param name="s"></param>   
    /// <returns></returns>   
    private static string String2Json(String s)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.Length; i++)
        {
            char c = s.ToCharArray()[i];
            switch (c)
            {
                case '\"':
                    sb.Append("\\\""); break;
                case '\\':
                    sb.Append("\\\\"); break;
                case '/':
                    sb.Append("\\/"); break;
                case '\b':
                    sb.Append("\\b"); break;
                case '\f':
                    sb.Append("\\f"); break;
                case '\n':
                    sb.Append("\\n"); break;
                case '\r':
                    sb.Append("\\r"); break;
                case '\t':
                    sb.Append("\\t"); break;
                default:
                    sb.Append(c); break;
            }
        }
        return sb.ToString();
    }

    /// <summary>   
    /// 格式化字元型、日期型、布林型   
    /// </summary>   
    /// <param name="str"></param>   
    /// <param name="type"></param>   
    /// <returns></returns>   
    private static string StringFormat(string str, Type type)
    {
        if (type == typeof(string))
        {
            str = String2Json(str);
            str = "\"" + str + "\"";
        }
        else if (type == typeof(DateTime))
        {
            str = "\"" + str + "\"";
        }
        else if (type == typeof(bool))
        {
            str = str.ToLower();
        }
        return str;
    } 
}