"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Tuesday, January 22, 2013

Convert a datatable to Json c#

Hi *.*,
I'm so happy today to introduce this.Last day by noon i got a crazy idea to create own json converter. i don't have a plan or an architecture how it goes, where to start. all what i had is a json string :). I finished that by 2 hr 50 min. :)

For the reusability of the code i created that by extension method. and i named the class JsonExtensionMethod class goes below.


public static class JsonExtensionMethod
{

    public static string ToJson(this DataTable dt)
    {
        string Json = string.Empty;
        string JSONObjectFormat = string.Empty;
        int i = 0;
        StringBuilder builder = new StringBuilder();
        string ColumnName = string.Empty;
        string MapValue = string.Empty;

        string JsonValue = string.Empty;
        try
        {
            string TableName = dt.TableName.ToString();
            foreach (DataColumn col in dt.Columns)
            {
                if (string.IsNullOrEmpty(JSONObjectFormat))
                    JSONObjectFormat = "\"" + col.ColumnName.ToString() + "\" : \"{" + i + "}\"";
                else
                    JSONObjectFormat = JSONObjectFormat + ",\"" + col.ColumnName.ToString() + "\" : \"{" + i + "}\"";
                i++;
            }
            for (int RowNumber = 0; RowNumber < dt.Rows.Count; RowNumber++)
            {
                object[] par = new object[dt.Columns.Count];
                for (int ColNumber = 0; ColNumber < dt.Columns.Count; ColNumber++)
                {
                    ColumnName = ColumnName == string.Empty ? dt.Rows[RowNumber][ColNumber].ToString() : ColumnName + "," + dt.Rows[RowNumber][ColNumber].ToString();
                    par[ColNumber] = dt.Rows[RowNumber][ColNumber].ToString();

                }
                MapValue = string.Format(JSONObjectFormat, par);
                if (string.IsNullOrEmpty(builder.ToString()))
                    builder.AppendLine("{" + MapValue + "}");
                else
                    builder.AppendLine(",{" + MapValue + "}");
                ColumnName = string.Empty;
                MapValue = string.Empty;
            }
            Json = string.Concat("[", builder.ToString(), "]");
        }
        catch (Exception)
        {

        }
        return Json;
    }
}



And my aspx and code behind goes below


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.9.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var summary = document.getElementById('<%= hdnJson.ClientID %>').value;
            var d = eval(summary);
            alert(d[0].Address);
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField ID="hdnJson" runat="server" />
    </div>
    </form>
</body>
</html>





protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable
        {
            Columns ={
                {"Myid",typeof(string)},
                {"Name"},
                {"Address"}
                }
        };
        dt.Rows.Add(1.ToString(), "Arun Aravind", "Kollam");
        dt.Rows.Add(1.ToString(), "Aru Aravind", "Kollam");
        dt.Rows.Add(1.ToString(), "Aun Aravind", "Kollam");
        dt.Rows.Add(1.ToString(), "Anu Aravind", "Kollam");
        dt.TableName = "Tbl";
        string Json = dt.ToJson();
        hdnJson.Value = Json;
    }




If u had any trouble just ask, Happy to help u :)
Stay Tune...
Have a nice day... 'N happy Coding :)

No comments: