Search code examples
datatablejson.net

How to return JSON object from DataTable of Sql Command in .Net Core 3.1


I want to return a JSON object while getting data from DataTable of Sql Command.

Here is my method:

       private static JSON ExecuteDatatableJSON(SqlCommand sqlCommand, int timeoutInSecs = 30)
       {
        DataTable dt = null;
        JSON json = null;

        try
        {
            dt = ExecuteDatatable(sqlCommand);
        }
        catch(Exception ex)
        {
            throw new Exception(ex.Message + ", Method: " + (new StackFrame().GetMethod().Name), ex);
        }

        json = JsonConvert.SerializeObject(dt); // this is the line causing issue

        return json;
        }

Solution

  • It requires to have DTO class with required number of properties and then loop over the Dto to bind the datatable fields with DTO properties.

    here is the example code

        product = new Product
     {
         title = dataTable.Rows[0]["ItemName"].ToString(),
         body_html = dataTable.Rows[0]["BodyHtml"].ToString(),
         vendor = dataTable.Rows[0]["Vendor"].ToString(),
         product_type = dataTable.Rows[0]["ProductType"].ToString(),
         variants = new Variant[1],
         images = new Image[1]
     }