How to covert a DataTable to Json Format?
<p>I am trying to convert the DataTable that I have fetched from the database to Json format. But I am getting an error. </p>

<pre><code>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;
    }
</code></pre>

<p>The above is the code for the conversion of the DataTable to Json format.</p>

<p>" Index was outside the bounds of the array. " is the error when debugging the code. This error occurs in the line</p>

<pre><code>if (data[0] == '[' || data[0] == '{')
</code></pre>