Saturday, 17 August 2013

DataSet Deserialization from Webservice

I observed that few of the webservices or REST services returns the DataSet with the xml read mode as DiffGram. But our requirement is to deserialize into collection of object of sepecified type. The deserialization of dataset is different from the normal xml or json deserialization. Please find the below steps to deserialize dataset.

Step1: Create the response to DataSet object as follows.
private DataSet GetDataSet(string url)
        {
            DataSet ds = new DataSet();
            using (var client = new WebClient())
            {
                var xml = client.DownloadString(sURL);
                using (var reader = XmlReader.Create(new StringReader(xml)))
                {
                    ds.ReadXml(reader, XmlReadMode.DiffGram);
                }
            }
            return ds;
        }
Step 2: Use the following helper method to Convert Data Table to Collection
 public static List<T> ToCollection<T>(this DataTable dt)
        {
            List<T> lst = new System.Collections.Generic.List<T>();
            Type tClass = typeof(T);
            PropertyInfo[] pClass = tClass.GetProperties();
            List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
            T cn;
            foreach (DataRow item in dt.Rows)
            {
                cn = (T)Activator.CreateInstance(tClass);
                foreach (PropertyInfo pc in pClass)
                {
                    // Can comment try catch block. 
                    try
                    {
                        DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                        if (d != null)
                            pc.SetValue(cn, item[pc.Name], null);
                    }
                    catch
                    {
                    }
                }
                lst.Add(cn);
            }
            return lst;
        }
Step 3: Use the methods as follows to Convert DataTable to collection
var ds= GetDataSet(url);
ds.Tables[DataTables.LotTable].ToCollection<Lot>();

I hope this helps you..

No comments:

Post a Comment