Quote of the day

Monday, June 24, 2013

Datatable to json string in c#


I had a requirement to convert a datatable into json string. I saw couple of code samples in stackoverflow and code project, but I wanted to write of my own to make it simple. Below is the code


private static string DataTableToJSON(DataTable table)
    {
        string delimiter = string.Empty;
        string comma = string.Empty;
        StringBuilder json = new StringBuilder("[");
        foreach (DataRow row in table.Rows)
        {
            json.Append(delimiter);
            json.Append("{");
            foreach (DataColumn col in table.Columns)
            {
                json.Append(comma);
                json.Append("\"" + col.ColumnName + "\":\"" + row[col.ColumnName].ToString() + "\"");
                comma = ",";
            }
            json.Append("}");
            comma = string.Empty;
            delimiter = ",";
        }
        json.Append("]");
        return json.ToString();
    }

Same code is given as image below: