如何将DataTable转换为Json格式?

时间:2016-06-03 09:34:26

标签: c# json

我正在尝试将从数据库中提取的DataTable转换为Json格式。但是我收到了一个错误。

public string ConvertTableToJSON(DataTable objDataTable)
    {
        ArrayList columnNames = new ArrayList();
        int rowCount = objDataTable.Rows.Count;
        int currentRow = 1;

        string json = "";

        //fetching column names
        foreach (DataColumn objColumn in objDataTable.Columns)
        {
            columnNames.Add(objColumn.ColumnName);
        }

        //generating json string for each row
        foreach (DataRow objRow in objDataTable.Rows)
        {
            json = json + "{";
            json = json + ConvertRowToJSON(objRow, columnNames);
            json = json + "}";

            if (currentRow != rowCount)
            {
                json = json + ",";
            }

            currentRow = currentRow + 1;
        }

        return json;
    }

以上是将DataTable转换为Json格式的代码。

"指数数组的边界之外。 "是调试代码时的错误。行

中出现此错误
if (data[0] == '[' || data[0] == '{')

2 个答案:

答案 0 :(得分:0)

此方法用于将数据表转换为json字符串

public string ConvertDataTabletoJSON(DataTable dt)
{

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}

它使用System.Web.Script.Serialization.JavaScriptSerializer将内容序列化为JSON格式:

答案 1 :(得分:0)

您可以使用JavaScriptSerializer将DataTable转换为JSON,方法是使用以下代码

public string DataTableToJsonWithJavaScriptSerializer(DataTable objDataTable)
{
 JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
 List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
 Dictionary<string, object> childRow;
 foreach (DataRow row in objDataTable.Rows)
 {
 childRow = new Dictionary<string, object>();
 foreach (DataColumn col in table.Columns)
 {
 childRow.Add(col.ColumnName, row[col]);
 }
 parentRow.Add(childRow);
 }
 return jsSerializer.Serialize(parentRow);
}

您可以使用Json.Net DLL并将数据表转换为json,如

public string DataTableToJsonWithJsonNet(DataTable objDataTable) 
{
   string jsonString=string.Empty;
   jsonString = JsonConvert.SerializeObject(objDataTable);
   return jsonString;
}

包括库。

  

Newtonsoft.Json;