DataTable转为JSON数据格式代码

public class DataTableConvertJson
{

#region dataTable转换成Json格式
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{\"");
jsonBuilder.Append(dt.TableName);
jsonBuilder.Append("\":[");
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("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}

#endregion dataTable转换成Json格式
#region DataSet转换成Json格式
/// <summary>
/// DataSet转换成Json格式
/// </summary>
/// <param name="ds">DataSet</param>
/// <returns></returns>
public static string Dataset2Json(DataSet ds)
{
StringBuilder json = new StringBuilder();

foreach (DataTable dt in ds.Tables)
{
json.Append("{\"");
json.Append(dt.TableName);
json.Append("\":");
json.Append(DataTable2Json(dt));
json.Append("}");
} return json.ToString();
}
#endregion

/// <summary>
/// Msdn
/// </summary>
/// <param name="jsonName"></param>
/// <param name="dt"></param>
/// <returns></returns>
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();
}
}

方法一:

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();
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。