Sunday, March 9, 2008

Json serialization of a DataTable - columns definition

Based on the existing example: http://www.dennydotnet.com/post/2007/09/A-DataTable-Serializer-for-ASPNET-AJAX.aspx and the explanation of a DataTable's json format:
http://weblogs.asp.net/infinitiesloop/archive/2006/12/14/ajax-futures-december-ctp-returning-datasets-datatables-and-datarows-from-a-webservice-or-pagemethod.aspx

I only added few lines of code to make it generate the simplest columns definition (names only) in the serialized structure to be friendlier with data-binding related methods like set_textProperty, etc in ASP.NET Futures scripts:

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            DataTable dt = obj as DataTable;
            Dictionary<string, object> result = new Dictionary<string, object>();

            if (dt != null && dt.Rows.Count > 0)
            {
                // List for row values
                List<object> rowValues = new List<object>();
                List<object> colDefinitions = new List<object>();

                foreach (DataColumn dc in dt.Columns)
                {
                    Dictionary<string, object> colDefinition = new Dictionary<string, object>();
                    colDefinition.Add("name", dc.ColumnName); // col name
                    colDefinitions.Add(colDefinition);
                }
                result["columns"] = colDefinitions;
                

                foreach (DataRow dr in dt.Rows)
                {
                    // Dictionary for col name / col value
                    Dictionary<string, object> colValues = new Dictionary<string, object>();

                    foreach (DataColumn dc in dt.Columns)
                    {
                        colValues.Add(dc.ColumnName, // col name
                         (string.Empty == dr[dc].ToString()) ? null : dr[dc]); // col value
                    }

                    // Add values to row
                    rowValues.Add(colValues);
                    //result.Add("row", colValues);
                }

                //// Add rows to serialized object
                result["rows"] = rowValues;
            }

            return result;
        }

No comments: