Convert datatable to JSON in C#

后端 未结 17 1108
猫巷女王i
猫巷女王i 2020-11-22 11:53
  1. I want to get records from database into a DataTable.
  2. Then convert the DataTable into a JSON object.
  3. Return the JSON ob
17条回答
  •  北海茫月
    2020-11-22 12:54

    You can use the same way as specified by Alireza Maddah and if u want to use two data table into one json array following is the way:

    public string ConvertDataTabletoString()
    {
    DataTable dt = new DataTable();
    DataTable dt1 = new DataTable();
    using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
    {
        using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List> rows = new List>();
            Dictionary row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            SqlCommand cmd1 = new SqlCommand("_another_query_", con);
                    SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
                    da1.Fill(dt1);
                    System.Web.Script.Serialization.JavaScriptSerializer serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
                    Dictionary row1;
                    foreach (DataRow dr in dt1.Rows) //use the old variable rows only
                    {
                        row1 = new Dictionary();
                        foreach (DataColumn col in dt1.Columns)
                        {
                            row1.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(row1); // Finally You can add into old json array in this way
                    }
            return serializer.Serialize(rows);
        }
    }
    }
    

    The same way can be used for as many as data tables as you want.

提交回复
热议问题