Sunday, 16 June 2013

How to convert Datatable to Json array.



Here I am going to give a sample code for converting datatable to json array. JSON is primarily a language that allows serializing javascript objects into strings. First I am reading  from xml and  creating datatable. Then by using JavaScriptSerializer I am converting to json array.


C# code:
               
public string GetEmployeeDetails()
        {
            string xmlPath = Server.MapPath("Employee.xml");
            DataSet ds = new DataSet();
            ds.ReadXml(xmlPath);
            DataTable dt = ds.Tables[0];
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 = null;
            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);
        }     

No comments:

Post a Comment