Convert JSON to Datatable or Dataset in C#

Codingvila
0
This article gives an explanation about how to convert JSON data into the DataTable or DataSet in asp.net web forms using c# and vb.net and also shows you how to convert JSON String to DataTable in ASP.Net and How to deserialize JSON data into Datatable or How to deserialized JSON data into Dataset as well as also show you how to convert JSON to DataTable c# and VB.Net.

In my previous articles, I explained the following articles that you might like to read.

Convert JSON to Datatable/Dataset in Asp.Net Web Forms with Bootstrap 4 Using C# and VB.Net

Many programmers who work with a Web form or Web API will have at least heard talk about JSON data. Even if any developers or programmers know on a basic level what is JSON data, they are not always certain How to Convert JSON String to Datatable or Dataset or how to convert the response of Web form or Web API from JSON to DataTable or JSON to Dataset in Asp.Net Web forms using C# and VB.Net, so in this article, I will show you how to convert JSON string to Datatable or Dataset step by step in asp.net web forms.

Requirement 

1) Create a New Asp.net web form Application with Bootstrap 4.
2) Create JSON data.text file with JSON String.
3) Read JSON String from JSONData.text file and Convert JSON String into Dtatable or DataSet.
4) Bind Datagridview using Dtatable and Display records in the tabular format.

Implementation

Let's start to implement read JSON string from the text file and convert JSON data into Datatable and Dataset and Bind data table to datagridview step by step.

Step 1: Open Your Visual Studio 2013 or higher versions.

Step 2: Go To File Menu and Create New Project and then Select "ASP.NET Empty Web Site", and Set project path location and Click on Ok. 

Step 3: Now, You have to add a Web form to the project and for that, you have to press right-click on your project name from Solution Explorer and Click on Add >> Add New Item.

Add New Item

Step 4: Again one popup window will appear on your screen where you have to select "Web Form" give the Name of Your Web form and finally Click on Add button.
NOTE: Make sure The file extension of your web form is (.aspx)
Step 5: Repeat Step 3 and Add the .text file with the name JSONData.text.

Add JSONData.text File

Now you have to write your JsonString in this file and while you run your web application with the following URL (http://localhost:13782/JsonData.txt)  you can see your JSON string in the web page.

JSON String

{
    "OrderTable": [
        {
			"OrderNumber": "CO-00001",
            "CustomerName": "Nikunj Satasiya",
            "OrderDate": "24/03/2019",
            "ProductName": "Laptop-Lenovo",
            "Pcs": "1",
            "Amount": "35000",
			"CGST": "9% (3150.00)",
			"SGST": "9% (3150.00)",
			"IGST": "0% (0.00)",
			"NetAmount": "41300.00"
        },
		{
			"OrderNumber": "CO-00002",
		    "CustomerName": "Hiren Dobariya",
            "OrderDate": "24/03/2019",
            "ProductName": "Laptop-Dell",
            "Pcs": "1",
            "Amount": "45000",
			"CGST": "9% (4050.00)",
			"SGST": "9% (4050.00)",
			"IGST": "0% (0.00)",
			"NetAmount": "53100.00"
        },
		{
			"OrderNumber": "CO-00003",
		    "CustomerName": "Vivek Ghadiya",
            "OrderDate": "24/03/2019",
            "ProductName": "TV-MI",
            "Pcs": "1",
            "Amount": "13500",
			"CGST": "9% (540.00)",
			"SGST": "9% (540.00)",
			"IGST": "0% (0.00)",
			"NetAmount": "14580.00"
        }
    ],
    "CompanyTable": [
        {
            "CompanyID": "C-0001",
            "CompanyName": "Lenovo",
            "Branch": "Surat"
        },
        {
            "CompanyID": "C-0001",
            "CompanyName": "Dell",
            "Branch": "Rajkot"
        },
        {
            "CompanyID": "C-0003",
            "CompanyName": "MI",
            "Branch": "Jamnagar"
        }
 
    ]
}
Step 6: if you didn't have a reference of newtonsoft.json then you need to add newtonsoft.json from the NuGet Manager. and for that Go to Tools >> NuGet Package Manager and click on Package Manager console as shown in the screen below.

Package Manager console

Step 7: Now, you have to write the following command in the Package Manager console.

PM> Install-Package Newtonsoft.Json

Install Package

This command will add the reference of Newtonsoft.Json to your project.

Step 8: After successful installation of the package you have to add the reference Newtonsoft.Json in your created web form  (Json-to-Datatable-Dataset.aspx.cs) file.

successful installation of the package

Step 9: Now you have to link CSS and Javascript for Bootstrap 4 before the end <head> tag.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
Step 10: Now you have to write the following code before the end <body> tag, here I have used two datagridview one for display data for Order Details and another for display data for Company Details and also for table one button. On click of control, we will convert JSON data into Dataset and Datatable and assign a data source to the appropriate datagridview and display the record in tabular format as per the given requirement.
<form id="form1" runat="server">
        <div class=" container card">
            <br />
            <h2>Order Detail</h2>
            <asp:GridView ID="grdOrderDetails" runat="server" CssClass="table table-bordered"></asp:GridView>
            <h2>Company Detail</h2>
            <asp:GridView ID="grdCompanyDetails" runat="server" CssClass="table table-bordered"></asp:GridView>
            <br />
            <div>
                <asp:Button ID="btnConvert" runat="server" CssClass="btn btn-primary" Text="Convert Json to Datatable & Dataset" OnClick="btnConvert_Click" />
            </div>
            <br />
        </div>
    </form>
Step 11: Then, You have to open the cs file of your web form  (Json-to-Datatable-Dataset.aspx.cs) and you need to add the following required Namespaces.

C#

using System.Data;
using System.IO;
using Newtonsoft.Json;

VB.NET

imports System.Data
imports System.IO
imports Newtonsoft.Json
Step 12: Now, You have to write the following code in the click event of the btnConvert button.

C#

protected void btnConvert_Click(object sender, EventArgs e)
{
    //Read Json Data From Text File 
     String Json = File.ReadAllText(Server.MapPath("~/JsonData.txt"));
 
     //Convert JSON Data to DataTable 
     //DataTable myDataTable = JsonConvert.DeserializeObject<DataTable>(Json);
 
 
     //Convert JSON Data to DataSet 
     DataSet myDataSet = JsonConvert.DeserializeObject<DataSet>(Json);
 
     
    //Check Table Count in DataSet
     if (myDataSet.Tables.Count > 0)
     {
         if (myDataSet.Tables[0].Rows.Count > 0)
         {
             //Bind Table[0] into grdOrderDetails GridView
             grdOrderDetails.DataSource = myDataSet.Tables[0];
             grdOrderDetails.DataBind();
         }
         else
         {
             grdOrderDetails.Visible = false;
         }
         if (myDataSet.Tables[1].Rows.Count > 0)
         {
             //Bind Table[1] into grdCompanyDetails GridView
             grdCompanyDetails.DataSource = myDataSet.Tables[1];
             grdCompanyDetails.DataBind();
         }
         else
         {
             grdCompanyDetails.Visible = false;
         }
     }
     
}

VB.Net

Protected Sub btnConvert_Click(sender As Object, e As EventArgsHandles btnConvert.Click
        'Read Json Data From Text File 
        Dim Json As String = File.ReadAllText(Server.MapPath("~/JsonData.txt"))
        'Convert JSON Data to DataTable 
        'DataSet myDataTable = JsonConvert.DeserializeObject<DataTable>(Json);
        'Convert JSON Data to DataSet 
        Dim myDataSet As DataSet = JsonConvert.DeserializeObject(Of DataSet)(Json)
        'Check Table Count in DataSet
        If (myDataSet.Tables.Count > 0) Then
            If (myDataSet.Tables(0).Rows.Count > 0) Then
                'Bind Table[0] into grdOrderDetails GridView
                grdOrderDetails.DataSource = myDataSet.Tables(0)
                grdOrderDetails.DataBind()
            Else
                grdOrderDetails.Visible = False
            End If
 
            If (myDataSet.Tables(1).Rows.Count > 0) Then
                'Bind Table[1] into grdCompanyDetails GridView
                grdCompanyDetails.DataSource = myDataSet.Tables(1)
                grdCompanyDetails.DataBind()
            Else
                grdCompanyDetails.Visible = False
            End If
 
        End If
 
    End Sub
NOTE: In this example I have Convert JSON data into Dataset, If you would like to Convert into Datatable then You Have to use Following code:
//Convert JSON Data to DataTable 
DataTable myDataTable = JsonConvert.DeserializeObject<DataTable>(Json);
Step 13: While you run your application and debug the code you can see the following JSON data and returned Dataset as I have shown on the screen.

Debug JSON data

Return Dataset

Output


Convert JSON to Datatable/Dataset

Summary

This article gives an explanation about converting JSON to DataTable or DataSet in Asp.Net Web forms with Bootstrap 4 using C# and Vb.Net with Example.

Post a Comment

0 Comments

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

Post a Comment
To Top