方法一:

public static string GetJSON(DataTable dt) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append("{\"totalCount\":" + dt.Rows.Count + ",\"data\":"); 
    sb.Append("["); 
    try 
    { 
        if (dt.Rows.Count > 0) 
        {
            Hashtable ht = new Hashtable();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ht.Add(i, dt.Columns[i].ColumnName);
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    sb.Append(string.Format("\"{0}\":\"{1}\",",
                    ht[j], dt.Rows[i][j].ToString()));
                }
                sb.Remove(sb.ToString().LastIndexOf(","), 1);
                sb.Append("},");
            }
            sb.Remove(sb.ToString().LastIndexOf(","), 1);
            ht.Clear();
            ht = null;
        }
    }  
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    finally
    {
         sb.Append("]}");
    }
    return sb.ToString();
} 


 

方法二:用Newtonsoft.Json.Net20.dll(点击下载)
先添加 Newtonsoft.Json.Net20.dll 的引用

using System.Data;
using System.IO;
using Newtonsoft.Json;

/// <summary>将DateTable转为Json格式数据</summary>
/// <param name="dt">要转换的DataTable名称</param>
/// <param name="dtName">应该是转换后的Key如用Json.dtName得到数据</param>
/// <returns></returns>
public static string DataTableToJSON(DataTable dt, string dtName)
{
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);

    using (JsonWriter jw = new JsonTextWriter(sw))
    {
        JsonSerializer ser = new JsonSerializer();
        jw.WriteStartObject();
        jw.WritePropertyName(dtName);
        jw.WriteStartArray();
        foreach (DataRow dr in dt.Rows)
        {
            jw.WriteStartObject();

            foreach (DataColumn dc in dt.Columns)
            {
                jw.WritePropertyName(dc.ColumnName);
                ser.Serialize(jw, dr[dc].ToString());
            }

            jw.WriteEndObject();
        }
        jw.WriteEndArray();
        jw.WriteEndObject();

        sw.Close();
        jw.Close();

    }

    return sb.ToString();
}





posted on 2011-03-11 09:27  墟零  阅读(3607)  评论(0编辑  收藏  举报