Convert Json to Datatable - C#

random

Convert Json to Datatable - C#

How to Convert JSON string to Datatable Back


In the previous articles I explained about JSON, Convert Datatable to JSON using C#. In this article I will explain how to change json object to c# datatable. Find the code below:-

json convert, convert json to datatable, convert to json, what is json format, convert array to json, c# .net
convert datatable to json object in asp.net C#
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Convert Json to Datatable in C# Language - ASP.Net</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h4>Convert JSON string to Datatable</h4>
            <asp:GridView ID="Gridview1" runat="server"></asp:GridView>
        </div>
    </form>
</body> 
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string jsonResult = "[{\"CustomerAddress\":\"Banglore\",\"CustomerId\":1,\"CustomerName\":\"Dell\"},{\"CustomerAddress\":\"New Delhi\",\"CustomerId\":2,\"CustomerName\":\"Sony\"}}]";
            DataTable dt = ConvertJSONToDataTable(jsonResult);

            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }
    }

    // C# Function to Convert Json string to C# Datatable
    protected DataTable ConvertJSONToDataTable(string jsonString)
    {
        DataTable dt = new DataTable();
        //strip out bad characters
        string[] jsonParts = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");

        //hold column names
        List<string> dtColumns = new List<string>();

        //get columns
        foreach (string jp in jsonParts)
        {
            //only loop thru once to get column names
            string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
            foreach (string rowData in propData)
            {
                try
                {
                    int idx = rowData.IndexOf(":");
                    string n = rowData.Substring(0, idx - 1);
                    string v = rowData.Substring(idx + 1);
                    if (!dtColumns.Contains(n))
                    {
                        dtColumns.Add(n.Replace("\"", ""));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error Parsing Column Name : {0}", rowData));
                }

            }
            break; // TODO: might not be correct. Was : Exit For
        }

        //build dt
        foreach (string c in dtColumns)
        {
            dt.Columns.Add(c);
        }
        //get table data
        foreach (string jp in jsonParts)
        {
            string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
            DataRow nr = dt.NewRow();
            foreach (string rowData in propData)
            {
                try
                {
                    int idx = rowData.IndexOf(":");
                    string n = rowData.Substring(0, idx - 1).Replace("\"", "");
                    string v = rowData.Substring(idx + 1).Replace("\"", "");
                    nr[n] = v;
                }
                catch (Exception ex)
                {
                    continue;
                }

            }
            dt.Rows.Add(nr);
        }
        return dt;
    }
}
I hope you will enjoy the C# programming tips while developing asp.net web application. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome. Also If you like this article, don't forget to share this article with your friends and colleagues.
Convert Json to Datatable - C# Reviewed by Ravi Kumar on 9:05 PM Rating: 5

No comments:

All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form

Name

Email *

Message *

Powered by Blogger.