locked
How to add to a json from table RRS feed

  • Question

  • User1839056048 posted

    Hi,

    I have a table employee with fields id,name,age.

    I want to add these records to a json table.

    how it is possible

    Regards

    Baiju

    Saturday, December 1, 2018 8:45 AM

All replies

  • User1724605321 posted

    Hi klbaiju ,

    You can firstly read the table to datatable using ADO.NET/EF , the convert to json using Json.Net DLL (Newtonsoft) :

    public string DataTableToJsonWithJsonNet(DataTable table) 
    {
       string jsonString=string.Empty;
       jsonString = JsonConvert.SerializeObject(table);
       return jsonString;
    }

    If i misunderstand your requirement , please feel free to let me know .

    Best Regards,

    Nan Yu

    Monday, December 3, 2018 2:54 AM
  • User-552477072 posted

    Hi klbaiju,

    You can use 

    public string ConvertDataTabletoString()
    {
             DataTable dt = new DataTable();
             using (SqlConnection con = new SqlConnection("Data Source=XXX;Initial Catalog=master;Integrated Security=true"))
             {
                   using (SqlCommand cmd = new SqlCommand("select id,name,age from employee", con))
                    {
                      con.Open();
                      SqlDataAdapter da = new SqlDataAdapter(cmd);
                      da.Fill(dt);
                      System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                      List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                       Dictionary<string, object> row;
                                   foreach (DataRow dr in dt.Rows)
                                    {
                                        row = new Dictionary<string, object>();
                                        foreach (DataColumn col in dt.Columns)
                                        {
                                             row.Add(col.ColumnName, dr[col]);
                                        } 
                                        rows.Add(row);
                                     }
                                    return serializer.Serialize(rows);
                          }
                    }
               }

    You just replace datasource (XXX) then it will take data from your table and covert to JSON. 

    Please don't forget to mark as Answer if it helps you! Thanks

    Friday, December 7, 2018 1:01 AM