Tuesday, 12 June 2012

Get JSON String from a DataTable in C#


using System.Text;

private string GetJSONString(DataTable Dt)
    {
        string RetVal = string.Empty;
        string[] StrDc = new string[Dt.Columns.Count];
        string HeadStr = string.Empty;

 StringBuilder Sb = new StringBuilder();
        string TempStr = string.Empty;
        int i = 0;
        int j = 0;

        try
        {
            for (i = 0; i <= Dt.Columns.Count - 1; i++)
            {
                StrDc[i] = Dt.Columns[i].Caption;
                HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
            }

            HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);

            Sb.Append("{\"" + Convert.ToString(Dt.TableName) + "\" : [");

            for (i = 0; i <= Dt.Rows.Count - 1; i++)
            {
                TempStr = HeadStr;
                Sb.Append("{");

                for (j = 0; j <= Dt.Columns.Count - 1; j++)
                {
                    TempStr = TempStr.Replace(Dt.Columns[j].ToString() + j.ToString() + "¾", Dt.Rows[i][j].ToString());
                }

                Sb.Append(TempStr + "},");
            }

            Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
            Sb.Append("]}");

            RetVal = Sb.ToString();
        }
        catch
        {
        }

        return RetVal;
    }

No comments:

Post a Comment