• Đăng ký
  • Đăng nhập

C# datatable to json

📅 — 👀 47 — 👦
//Method 1:
using Newtonsoft.JSON;

public string DataTableToJSONWithJSONNet(DataTable table) {
   string JSONString=string.Empty;
   JSONString = JSONConvert.SerializeObject(table);
   return JSONString;
}

//Method 2:
using System.Web.Script.Serialization;

public string DataTableToJSONWithJavaScriptSerializer(DataTable table)
{
    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
    List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> ();
    Dictionary < string, object > childRow;
    foreach(DataRow row in table.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);
}

//Method 3:
public string DataTableToJSONWithStringBuilder(DataTable table)
{
    var JSONString = new StringBuilder();
    if (table.Rows.Count > 0)
    {
        JSONString.Append("[");
        for (int i = 0; i < table.Rows.Count; i++)
        {
            JSONString.Append("{");
            for (int j = 0; j < table.Columns.Count; j++)
            {
                if (j < table.Columns.Count - 1)
                {
                    JSONString.Append("\\"" + table.Columns[j].ColumnName.ToString() + "\\":" + "\\"" + table.Rows[i][j].ToString() + "\\",");
                }
                else if (j == table.Columns.Count - 1)
                {
                    JSONString.Append("\\"" + table.Columns[j].ColumnName.ToString() + "\\":" + "\\"" + table.Rows[i][j].ToString() + "\\"");
                }
            }
            if (i == table.Rows.Count - 1)
            {
                JSONString.Append("}");
            }
            else
            {
                JSONString.Append("},");
            }
        }
        JSONString.Append("]");
    }
    return JSONString.ToString();
}