Converting Between JSON And Datatables In C#

Datatable in C#

The DataTable class in C# ADO.NET is a database table representation and provides a collection of columns and rows to store data in a grid form. The code sample in this article explains how to create a DataTable at run-time in C#. You will also learn how to create DataTable columns and rows, add data to a DataTable and bind a DataTable to a DataGridView control using data binding`` you can see more about Datatable in this Article

JSON

(JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.  see JSON

SuperConvert is an open-source lightweight package to convert between many data types,

It also contains a Hijri date helper (which will be discussed in future articles). see Using SuperConvert

In order to start converting between Datatables and JSON, we must first install SuperConvert in our project.

Create a new project

Converting Between JSON And Datatables In C#

Install SuperConvert using the NuGet package manager 

Converting Between JSON And Datatables In C#

Or by running this command 

Run the following NuGet command (recommended to install the latest version always)

Install-Package SuperConvert -Version 1.0.3.3

Start coding by adding the using statement

//Adding the reference
using SuperConvert.Extentions;

Our JSON string needs to be converted to Datatable must be a list of objects, after that, we can call the extension method .ToDatatable()

//Json to dataTable
string customers = "[{\"CompanayID\":\"k123\",\"Role\":\"Admin\",\"Country\":\"UK\",\"Asset\":\"HD\",\"incident\":null}, {\"CompanayID\":\"k234\",\"Role\":\"User\",\"Country\":\"US\",\"Asset\":\"HD12\",\"incident\":\"abc 1\"}]";
DataTable dt = customers.ToDataTable("TableName");

We can pass a table name to .ToDataTable("") or we can just leave it. and now we have a Datatable containing all our JSON objects.

Datatable to JSON

If we need to convert the Datatable back we just have to call the extension method .ToJson()

//DataTable to json
string json = dt.ToJson();
Console.WriteLine($"Json: \n {json} \n");

Summary

  1. Create a project
  2. Install SuperConvert
  3. Start converting between data types 

** It also contains another data converters (CSV, JSON, Datatable, DateTime, XML, ASCII Encoding)