Convert JSON Data to DataTable or DataSet in .NET Core Using C#

watch_later 10/05/2024

In modern web development, JSON (JavaScript Object Notation) has become the standard format for transmitting data, particularly between a client and server. Understanding how to efficiently convert JSON data into a DataTable or DataSet is crucial for .NET developers working with API responses or file inputs. This article will walk you through converting JSON data into a DataTable or DataSet in a .NET Core application using C#, providing a clear step-by-step guide for implementation.

Convert JSON Data to DataTable or DataSet in .NET Core Using C#

Key Concepts Covered:

  1. Convert JSON to DataTable in .NET Core
  2. Convert JSON to DataSet in .NET Core
  3. Deserialize JSON into .NET Core objects
  4. Bind data to GridView for display in a web application

Prerequisites:

  • Visual Studio 2019 or higher
  • Basic knowledge of JSON and .NET Core
  • Newtonsoft.Json NuGet package

Requirements for the Implementation:

  1. Create a .NET Core Web Application.
  2. Read JSON data from a file.
  3. Convert JSON data to DataTable or DataSet.
  4. Bind DataTable to a grid for data display.

Step-by-Step Guide to Convert JSON to DataTable or DataSet in .NET Core

Step 1: Set Up the .NET Core Project

Open Visual Studio and follow these steps:

  • Go to File > New > Project.
  • Select ASP.NET Core Web Application, then choose Empty for the project template.
  • Set the project path and click Create.

Step 2: Install the Newtonsoft.Json Package

You need to add a reference to the Newtonsoft.Json library to handle JSON data. Use the NuGet Package Manager to install it:

  1. Go to Tools > NuGet Package Manager > Package Manager Console.
  2. In the console, type the following command:
    Install-Package Newtonsoft.Json

This will install the required library for JSON serialization and deserialization.

Step 3: Add a JSON File for Testing

Next, add a sample JSON file to the project:

  1. Right-click on the root folder and select Add > New Item.
  2. Choose Text File and name it JSONData.txt.
  3. Insert the following JSON data into the file:
    {
       "OrderTable": [
          {
             "OrderNumber": "CO-00001",
             "CustomerName": "Nikunj Satasiya",
             "OrderDate": "05/10/2024",
             "ProductName": "Laptop-Dell",
             "Pcs": "1",
             "Amount": "35000",
             "CGST": "9% (3150.00)",
             "SGST": "9% (3150.00)",
             "NetAmount": "41300.00"
          }
       ]
    }

Step 4: Create the Razor Page or MVC View for Display

Now, add a new Razor Page or MVC view to the project to display the data:

  1. Right-click on the Pages folder, select Add > Razor Page.
  2. Name the page JsonToDataTable.
  3. In the newly created Razor Page, replace the content of the view with a simple form:
    <form method="post">
        <div>
            <h2>Order Details</h2>
            <table id="gridOrderDetails" class="table table-bordered"></table>
            <button type="submit" class="btn btn-primary">Convert JSON to DataTable</button>
        </div>
    </form>

Step 5: Write the Backend Logic to Deserialize JSON Data

In your JsonToDataTable.cshtml.cs file, you will handle reading and converting the JSON data.

  1. First, import the necessary namespaces:
    using System.Data;
    using System.IO;
    using Newtonsoft.Json;
  2. Then, create a method to read and deserialize the JSON file into a DataSet:
    public IActionResult OnPost()
    {
        // Read JSON data from the text file
        string jsonData = System.IO.File.ReadAllText("root/JSONData.txt");
     
        // Convert JSON data to DataSet
        DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(jsonData);
     
        // Bind DataTable to View (You can return this to a Grid in the View)
        if (dataSet.Tables.Count > 0)
        {
            ViewData["OrderTable"] = dataSet.Tables[0];
        }
     
        return Page();
    }

This code reads the JSON file and converts it to a DataSet. The first table of the DataSet is passed to the view using ViewData.

Step 6: Display the Data in a Table

Back in your Razor Page, bind the DataTable to a simple HTML table. Modify the view like this:

@if (ViewData["OrderTable"] != null)
{
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Order Number</th>
                <th>Customer Name</th>
                <th>Order Date</th>
                <th>Product Name</th>
                <th>Pcs</th>
                <th>Amount</th>
                <th>Net Amount</th>
            </tr>
        </thead>
        <tbody>
            @foreach (DataRow row in ((DataTable)ViewData["OrderTable"]).Rows)
            {
                <tr>
                    <td>@row["OrderNumber"]</td>
                    <td>@row["CustomerName"]</td>
                    <td>@row["OrderDate"]</td>
                    <td>@row["ProductName"]</td>
                    <td>@row["Pcs"]</td>
                    <td>@row["Amount"]</td>
                    <td>@row["NetAmount"]</td>
                </tr>
            }
        </tbody>
    </table>
}

This will render the OrderTable data into the HTML table when the user clicks the "Convert JSON to DataTable" button.

Step 7: Run the Application

Now, run your application and navigate to the Razor Page where you'll see the converted JSON data displayed in a tabular format.

Summary

In this article, we explored how to convert JSON data into a DataTable or DataSet in .NET Core using C#. We walked through a step-by-step example of reading a JSON file, deserializing the data, and displaying it using a simple table. JSON data is essential in modern applications, and understanding how to process it efficiently in .NET Core will significantly improve your backend data handling capabilities.

Tags:

  • Convert JSON to DataTable .NET Core
  • Convert JSON to DataSet in .NET Core
  • Deserialize JSON in .NET Core
  • JSON to DataTable conversion C#
  • Bind JSON to DataTable in .NET Core

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

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

sentiment_satisfied Emoticon