Convert JSON to Datatable C# Example

Convert JSON to Datatable C#

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format for storing and exchanging data. It is easy for machines to parse and generate. So in this C# tutorial, we will learn about how to convert JSON to datatable in asp.net c#.

The following example demonstrates how to convert JSON array to datatable in c#:-

<%@ 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 data into datatable in c#</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1>Convert json string to dataset c#</h1>
            <div>
                [	
                    {
 		                "CustomerAddress": "Banglore",
 		                "CustomerId": 1,
 		                "CustomerName": "Dell"
 	                },
 	                {
 		                "CustomerAddress": "New Delhi",
 		                "CustomerId": 2,
 		                "CustomerName": "Sony"
 	                } ]
            </div>
            <br />
            <asp:GridView ID="Gridview1" runat="server"></asp:GridView>
        </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;

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();
        }
    }

    // how to convert json to datatable in asp.net c#
    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;
    }
}

Download Code

Also, you can use third-party library Json.Net | A popular high-performance JSON framework for .NET and it is very useful with less code and high-performance conversion of JSON to C# objects.

What do you think?

I hope you liked this article. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

LEAVE A REPLY

Please enter your comment!
Please enter your name here