-->

Convert JSON to a Typed DataTable in C# (Student Example)

To convert JSON to a DataTable in C#, deserialize the JSON into a known model, create columns with explicit .NET types, and add each model's values as a row. The Student example uses Id, Name, Age and City. An explicit schema is useful when a GridView, reporting tool or existing ADO.NET component needs stable column names and types.

The complete example uses Newtonsoft.Json 13.0.4 in a modern .NET console project. It validates the flat student records before adding rows, then shows a separate nested-course projection with one row per course. For direct JSON-to-DataTable/DataSet inference in C# and VB.NET, see the general JSON conversion guide.

Short Answer

Use an explicit DataTable schema when a report needs stable column names and types, including when the input array is empty. Deserialize and validate the Student model before adding rows, and project nested courses separately when the intended result is one row per course.

JSON to DataTable conversion in C#
The original JSON-to-DataTable topic illustration.

Step 1: Create the project and install the package

Use a supported .NET SDK. These setup commands target .NET 10; Visual Studio users need a version that supports that SDK, such as Visual Studio 2026. The conversion classes also use APIs available on .NET 8, but an installed SDK must support the target you select.

shell
dotnet new console -n StudentJsonTable --framework net10.0
cd StudentJsonTable
dotnet add package Newtonsoft.Json --version 13.0.4

The versioned NuGet page documents this package version. The article uses Json.NET explicitly; installing it does not change the default JSON formatter of an ASP.NET Core application.

Step 2: Save the original sample as students.json

json
[
  {
    "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"
  }
]

This is a JSON array of objects. Property names and string values use double quotes. Keep a long identifier as a JSON string and use a corresponding string column if its leading zeros or exact digits matter; the example's Id is deliberately a positive 32-bit integer.

Step 3: Add StudentTable.cs

csharp
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;

namespace Codingvila.JsonTables
{
    public sealed class Student
    {
        [JsonProperty(Required = Required.Always)]
        public int Id { get; set; }
        [JsonProperty(Required = Required.Always)]
        public string Name { get; set; } = string.Empty;
        [JsonProperty(Required = Required.Always)]
        public int Age { get; set; }
        [JsonProperty(Required = Required.Always)]
        public string City { get; set; } = string.Empty;
    }

    public static class StudentTable
    {
        public static DataTable FromJson(string json)
        {
            if (string.IsNullOrWhiteSpace(json) || json.Length > 1000000)
                throw new ArgumentException("Provide JSON within the example's size limit.", nameof(json));

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.None,
                MissingMemberHandling = MissingMemberHandling.Error,
                CheckAdditionalContent = true,
                MaxDepth = 16
            };
            var students = JsonConvert.DeserializeObject<List<Student>>(json, settings)
                ?? throw new JsonSerializationException("A JSON array is required, not null.");
            if (students.Count > 10000)
                throw new ArgumentException("This example supports at most 10,000 students.", nameof(json));

            var table = new DataTable("Students");
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Age", typeof(int));
            table.Columns.Add("City", typeof(string));
            try
            {
                foreach (var student in students)
                {
                    if (student == null || student.Id <= 0 || student.Age < 0 || student.Age > 150
                        || string.IsNullOrWhiteSpace(student.Name) || student.Name.Length > 100
                        || string.IsNullOrWhiteSpace(student.City) || student.City.Length > 200)
                        throw new ArgumentException("A student does not satisfy the example's validation rules.", nameof(json));
                    table.Rows.Add(student.Id, student.Name, student.Age, student.City);
                }
                return table;
            }
            catch
            {
                table.Dispose();
                throw;
            }
        }
    }
}

The model requires all four fields, and unknown properties are rejected by MissingMemberHandling.Error. Name and City cannot be null or whitespace. The age range of 0–150, name/city lengths, 10,000-row cap and 1,000,000-character input cap are explicit demonstration rules; adjust them to the real domain. The character limit is checked after a file has been read and is not an HTTP upload-byte limit.

The DataTable always has the same four columns, even for an empty array. Json.NET reads integer fields according to the model; incompatible values cause a conversion error. The routine rejects a null root or null student record. It does not infer a schema from whichever properties happen to appear first, and it does not enable automatic CLR type-name handling for input JSON.

Step 4: Replace Program.cs and run it

csharp
using Codingvila.JsonTables;
using Newtonsoft.Json;
using System;
using System.Data;
using System.IO;

try
{
    string json = File.ReadAllText("students.json");
    using DataTable table = StudentTable.FromJson(json);
    foreach (DataRow row in table.Rows)
        Console.WriteLine($"Id: {row["Id"]}, Name: {row["Name"]}, Age: {row["Age"]}, City: {row["City"]}");
    return 0;
}
catch (Exception error) when (error is IOException || error is UnauthorizedAccessException
    || error is JsonException || error is ArgumentException)
{
    Console.Error.WriteLine("Conversion failed: " + error.Message);
    return 1;
}
shell
dotnet run

Run from the project folder so students.json resolves to the file you created. The catch filter reports local file, JSON and validation failures and returns a nonzero exit code. An API should translate validation failures into its own appropriate response without exposing private file paths or raw parser messages.

text
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

The caller disposes the returned table after use. In a UI application, bind or consume it while it is alive. In an ASP.NET Core API, prefer returning a deliberately designed response DTO rather than exposing an internal DataTable as an accidental wire contract.

Nested JSON: choose one row per course

A child array requires a deliberate row shape. The original nested example contains one student and two courses:

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

To obtain columns StudentId, Name, CourseName and Grade, add the following as CourseTable.cs. It repeats the student's ID and name once per course. This is a specific projection for this schema, not a generic recursive flattening algorithm.

csharp
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;

namespace Codingvila.JsonTables
{
    public sealed class StudentWithCourses
    {
        [JsonProperty(Required = Required.Always)]
        public int StudentId { get; set; }
        [JsonProperty(Required = Required.Always)]
        public string Name { get; set; } = string.Empty;
        [JsonProperty(Required = Required.Always)]
        public List<Course> Courses { get; set; } = new List<Course>();
    }

    public sealed class Course
    {
        [JsonProperty(Required = Required.Always)]
        public string CourseName { get; set; } = string.Empty;
        [JsonProperty(Required = Required.Always)]
        public string Grade { get; set; } = string.Empty;
    }

    public static class CourseTable
    {
        public static DataTable FromJson(string json)
        {
            if (string.IsNullOrWhiteSpace(json) || json.Length > 1000000)
                throw new ArgumentException("Provide JSON within the example's size limit.", nameof(json));
            var student = JsonConvert.DeserializeObject<StudentWithCourses>(json,
                new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.None,
                    MissingMemberHandling = MissingMemberHandling.Error,
                    CheckAdditionalContent = true,
                    MaxDepth = 16
                }) ?? throw new JsonSerializationException("A student object is required.");
            if (student.StudentId <= 0 || string.IsNullOrWhiteSpace(student.Name)
                || student.Name.Length > 100 || student.Courses == null || student.Courses.Count > 10000)
                throw new ArgumentException("Invalid student or course count.", nameof(json));

            var table = new DataTable("StudentCourses");
            table.Columns.Add("StudentId", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("CourseName", typeof(string));
            table.Columns.Add("Grade", typeof(string));
            try
            {
                foreach (var course in student.Courses)
                {
                    if (course == null || string.IsNullOrWhiteSpace(course.CourseName)
                        || course.CourseName.Length > 200 || string.IsNullOrWhiteSpace(course.Grade)
                        || course.Grade.Length > 20)
                        throw new ArgumentException("Invalid course values.", nameof(json));
                    table.Rows.Add(student.StudentId, student.Name, course.CourseName, course.Grade);
                }
                return table;
            }
            catch
            {
                table.Dispose();
                throw;
            }
        }
    }
}

Save the nested input as student-courses.json. In Program.cs, replace the file-read, conversion and loop inside the existing try block with:

csharp
string json = File.ReadAllText("student-courses.json");
using DataTable table = CourseTable.FromJson(json);
foreach (DataRow row in table.Rows)
    Console.WriteLine($"{row["StudentId"]} | {row["Name"]} | {row["CourseName"]} | {row["Grade"]}");
text
1 | Nikunj Satasiya | Math | A
1 | Nikunj Satasiya | Science | B

An empty Courses array produces a table with headers and no course rows. If students with no courses must appear, choose a different documented rule, such as a row with DBNull course values or two related tables in a DataSet. The method does not create parent/child relations automatically.

Troubleshooting and limits

  • Object instead of array: the flat routine expects [...]. A wrapper such as {"Students":[...]} must be represented by a wrapper model or explicitly unwrapped.
  • Unexpected fields: the strict flat model rejects extra properties such as Courses. Use the nested routine for that separate input shape.
  • Null values: this example rejects null required values. If the domain permits null, use nullable model properties and explicitly write DBNull.Value into the matching DataTable cells.
  • Large JSON: this approach holds the source text, model list and DataTable in memory. A DataTable is not required for ordinary JSON processing; use typed records directly or a streaming design when they fit the task.
  • Web API input: enforce transport limits, authentication and row authorization at the endpoint. This local conversion helper supplies none of those application controls.

Use the Web Forms two-GridView example when binding named tables to classic server controls, or the ASP.NET Core Razor Pages example for a server-rendered Core page. Those are different hosting workflows built around the same underlying tabular-data concepts.

Conclusion

The flat Student conversion produces four predictable columns and validates each record before it becomes a DataRow. The nested example makes its row rule explicit by repeating the student details once per course. Use these mappings when a tabular consumer needs them, retain the documented empty-input behavior, and keep request limits and authorization in the surrounding application.

About the author

Nikunj Satasiya

Software Engineer

Nikunj Satasiya writes practical tutorials on C#, ASP.NET Core, SQL Server, and Angular at Codingvila. He explains development workflows through focused code examples, clear reasoning, and troubleshooting guidance.

Join the discussion

Ask a question or share an implementation detail. Comments are reviewed before publication.