How to Convert JSON to DataTable in C#

watch_later 1/04/2025

In the world of web and application development, data exchange between systems often happens in the form of JSON (JavaScript Object Notation) due to its lightweight and human-readable structure.

However, many applications, particularly those built using C#, require this JSON data to be processed and displayed in tabular form for easier manipulation and querying. This is where converting JSON to a DataTable in C# comes into play.

In this article, we will provide a step-by-step guide to convert JSON to DataTable in C# and explore various methods and techniques for JSON to DataTable conversion in .NET Core and ASP.NET Core Web APIs.

How to Convert JSON to DataTable in C#

Whether you're working on JSON to DataTable C# Example, JSON Parsing to DataTable, or looking for the best way to convert JSON to DataTable in C#, this article will equip you with the knowledge and examples you need to implement this functionality seamlessly.

Understanding JSON and DataTable

Before diving into the JSON to DataTable conversion process, it’s important to understand what JSON and DataTables are.

  1. JSON (JavaScript Object Notation): A lightweight, text-based format for data exchange. It is easy for humans to read and write and easy for machines to parse and generate. JSON is commonly used in APIs for transmitting data between the server and client.
  2. DataTable: A DataTable is a collection of data in tabular form. It is a powerful feature of the ADO.NET framework in C# that allows you to store and manipulate data in-memory. DataTables are often used to hold data retrieved from databases, web services, or APIs.

Why Convert JSON to DataTable in C#?

There are several reasons why you might want to convert JSON to DataTable in C#:

  • Data Presentation: In many scenarios, JSON data needs to be displayed in a tabular format in a grid view (e.g., ASP.NET Web Forms, WinForms, etc.).
  • Data Manipulation: DataTables provide powerful methods and properties for filtering, sorting, and querying data, which can be extremely useful when working with large datasets.
  • Integration with ADO.NET: Many applications rely on ADO.NET to interact with relational databases, and DataTables are the primary way to work with in-memory data in this environment.
  • API Responses: When consuming data from APIs (such as Parse JSON to DataTable in Web API), it’s often necessary to convert the response into a DataTable to process and display it.

How to Convert JSON to DataTable in C# - The Basic Approach

There are different ways to read JSON into a DataTable in C#. Let's break down some of the best ways to convert JSON to DataTable in C#, starting with a simple example and then moving towards more complex cases such as nested JSON or complex JSON structures.

In this example, we will take a JSON response containing students’ data and convert it into a DataTable.

Example JSON Data

Let's consider a simple JSON object representing students:

[
  {
    "Id": 1,
    "Name""Nikunj Satasiya",
    "Age": 25,
    "City""Ahmedabad"
  },
  {
    "Id": 2,
    "Name""Mansi Satasiya",
    "Age": 24,
    "City""Surat"
  },
  {
    "Id": 3,
    "Name""Hiren Dobariya",
    "Age": 26,
    "City""Vadodara"
  },
  {
    "Id": 4,
    "Name""Vivek Ghadiya",
    "Age": 27,
    "City""Rajkot"
  },
  {
    "Id": 5,
    "Name""Krishna Patel",
    "Age": 28,
    "City""Bhavnagar"
  }
]

Step 1: Deserialize JSON into C# Object

In the first step, we’ll deserialize the JSON string into a C# object (a list of students in this case). We can use the JsonConvert class from the Newtonsoft.Json library, which is a popular library for handling JSON in C#.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
 
public class Student
{
    public int Id { getset; }
    public string Name { getset; }
    public int Age { getset; }
    public string City { getset; }
}
 
public class Program
{
    public static void Main()
    {
        string jsonString = "[{\"Id\":1,\"Name\":\"Nikunj Satasiya\",\"Age\":25,\"City\":\"Ahmedabad\"},"
                            + "{\"Id\":2,\"Name\":\"Mansi Satasiya\",\"Age\":24,\"City\":\"Surat\"},"
                            + "{\"Id\":3,\"Name\":\"Hiren Dobariya\",\"Age\":26,\"City\":\"Vadodara\"},"
                            + "{\"Id\":4,\"Name\":\"Vivek Ghadiya\",\"Age\":27,\"City\":\"Rajkot\"},"
                            + "{\"Id\":5,\"Name\":\"Krishna Patel\",\"Age\":28,\"City\":\"Bhavnagar\"}]";
 
        List<Student> students = JsonConvert.DeserializeObject<List<Student>>(jsonString);
 
        // Output the deserialized data
        foreach (var student in students)
        {
            Console.WriteLine($"Id: {student.Id}, Name: {student.Name}, Age: {student.Age}, City: {student.City}");
        }
    }
}

Step 2: Convert C# Object to DataTable

Now that we have the list of student objects, we can convert this list into a DataTable. The Convert JSON to DataTable in C# function will map the JSON object properties (like Id, Name, Age, and City) to the columns in the DataTable.

Here's the method for converting the deserialized JSON data into a DataTable in C#:

using System;
using System.Collections.Generic;
using System.Data;
 
public static class JsonToDataTableConverter
{
    public static DataTable ConvertToDataTable(List<Student> students)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id"typeof(int));
        dt.Columns.Add("Name"typeof(string));
        dt.Columns.Add("Age"typeof(int));
        dt.Columns.Add("City"typeof(string));
 
        foreach (var student in students)
        {
            dt.Rows.Add(student.Id, student.Name, student.Age, student.City);
        }
 
        return dt;
    }
}

Step 3: Using the Conversion Method

Now, let’s use the ConvertToDataTable method to convert the list of students into a DataTable:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
 
public class Program
{
    public static void Main()
    {
        string jsonString = "[{\"Id\":1,\"Name\":\"Nikunj Satasiya\",\"Age\":25,\"City\":\"Ahmedabad\"},"
                            + "{\"Id\":2,\"Name\":\"Mansi Satasiya\",\"Age\":24,\"City\":\"Surat\"},"
                            + "{\"Id\":3,\"Name\":\"Hiren Dobariya\",\"Age\":26,\"City\":\"Vadodara\"},"
                            + "{\"Id\":4,\"Name\":\"Vivek Ghadiya\",\"Age\":27,\"City\":\"Rajkot\"},"
                            + "{\"Id\":5,\"Name\":\"Krishna Patel\",\"Age\":28,\"City\":\"Bhavnagar\"}]";
 
        List<Student> students = JsonConvert.DeserializeObject<List<Student>>(jsonString);
        DataTable dt = JsonToDataTableConverter.ConvertToDataTable(students);
 
        // Display DataTable
        foreach (DataRow row in dt.Rows)
        {
            Console.WriteLine($"Id: {row["Id"]}, Name: {row["Name"]}, Age: {row["Age"]}, City: {row["City"]}");
        }
    }
}

Advanced Topics: Converting Nested JSON to DataTable

In some cases, you may need to convert nested JSON to DataTable. Nested JSON objects present a challenge because DataTables work best with flat structures. However, using recursive methods or flattening the JSON structure can help in such cases.

Here's an example of how to handle nested JSON:

{
    "StudentId": 1,
    "Name""Nikunj Satasiya",
    "Courses": [
        { "CourseName""Math""Grade""A"},
        { "CourseName""Science""Grade""B"}
    ]
}

JSON to DataTable in Web API and ASP.NET Core

When working with Web APIs or ASP.NET Core, the process remains largely the same. You receive a JSON response from the API, deserialize it into C# objects, and then convert it into a DataTable for further processing. For a JSON to DataTable C# Web API example, you can follow similar steps, but make sure to implement the necessary HTTP client code to fetch the JSON data from the API before performing the conversion.

Conclusion

Converting JSON to DataTable in C# is a common and necessary task when dealing with JSON data in enterprise applications. Whether you're working with nested JSON, complex JSON objects, or simply parsing JSON to DataTable in Web API, the methods outlined in this article will help you streamline the process. By utilizing JSON deserialization, C# collections, and DataTable conversion, you can efficiently manage and manipulate JSON data in your .NET Core or ASP.NET Core applications.

With examples like Converting JSON to DataTable C#, Deserialize JSON to DataTable in C#, and best practices for handling JSON data to DataTable conversion, you can now implement these solutions effectively within your applications.

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