How to convert datatable to json string using json.net?

Maybe it could help

Original version

public static class DataTableToJson
{
    public static JArray ToJson(this System.Data.DataTable source)
    {
        JArray result = new JArray();
        JObject row;
        foreach (System.Data.DataRow dr in source.Rows)
        {
            row = new JObject();
            foreach (System.Data.DataColumn col in source.Columns)
            {
                row.Add(col.ColumnName.Trim(), JToken.FromObject(dr[col]));
            }
            result.Add(row);
        }
        return result;
    }
}

Edited Version

There is a intermediate step because I needed to have a dictionary

public static IEnumerable<Dictionary<string, object>> ToDictionary(this DataTable table)
{
    string[] columns = table.Columns.Cast<DataColumn>().Select(c=>c.ColumnName).ToArray();
    IEnumerable<Dictionary<string, object>>  result = table.Rows.Cast<DataRow>()
            .Select(dr => columns.ToDictionary(c => c, c=> dr[c]));
    return result;
}

You can add JsonConverter.SerializeObject(result);, or another json serializer to get json string.

This is similar to @Hasan Javaid post


string json = JsonConvert.SerializeObject(table, Formatting.Indented);

Edit: You don't need indented formatting, of course, but it makes it nice and readable.