Wednesday, 10 April 2013

HOW TO CONVERT DATATABLE TO JSON FORMAT IN ASP.NET USING C#

Definition and introduction :--

JSON is built on two pillers :

  1) A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

  2) An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Fore more study and info please visit  http://en.wikipedia.org/wiki/JSON 


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for machines to parse and generate. JSON is a text format that is completely language independent.


Write Function To do the same:


public static string ConvertTableToJSON(DataTable objDataTable)
        {
            string[] jsonArr = new string[objDataTable.Columns.Count];
            string headString = string.Empty;
            for (int i = 0; i < objDataTable.Columns.Count; i++)
            {
                jsonArr [i] = objDataTable.Columns[i].Caption;
                headString += "'" + jsonArr [i] + "' : '" + jsonArr [i] + i.ToString() + "¾" + "',";
            }

            headString = headString.Substring(0, headString.Length - 1);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");

            if (objDataTable.Rows.Count > 0)
            {
                for (int i = 0; i < objDataTable.Rows.Count; i++)
                {
                    string tempString = headString;
                    sb.Append("{");
                    for (int j = 0; j < objDataTable.Columns.Count; j++)
                    {
                        tempString = tempString.Replace(objDataTable.Columns[j] + j.ToString() + "¾", objDataTable.Rows[i][j].ToString());
                    }

                    sb.Append(tempString + "},");
                }
            }
            else
            {
                string tempString = headString;
                sb.Append("{");
                for (int j = 0; j < objDataTable.Columns.Count; j++)
                {
                    tempString = tempString.Replace(objDataTable.Columns[j] + j.ToString() + "¾", "-");
                }

                sb.Append(tempString + "},");
            }

            sb = new StringBuilder(sb.ToString().Substring(0, sb.ToString().Length - 1));
            sb.Append("]");
            return sb.ToString();
        }
I think it would be benificial for you....:--

No comments:

Post a Comment