Data Conversions in C# with SuperConvert

Introduction

In this article, I will demonstrate the SuperConvert Nuget package to help developers convert JSON, XML, CSV, XLS, and more. SuperConvert is a powerful Nuget package for data conversion in C#. SuperConvert. Abstraction has a SuperConvertExcelService that makes it easy for developers to convert data between various formats, such as CSV, JSON, DATATABLE, and XLS.

It supports various data conversions like JSON to Datatable, Convert Datatable to JSON, JSON to CSV, DataTable to CSV, CSV to JSON, CSV to DataTable, JSON to XLS, and Datatable to XLS.

Data Conversion in C# using SuperConvert.Abstraction Nuget Library

Data Conversion Like Never Before in C# using SuperConvert.Abstraction Nuget Library.

Here, I will demonstrate the below-listed conversion from one type to another. refer documentation for SuperConvert library SuperConvert Documentation and Redefining Data Conversions for Seamless Simplicity and Efficiency

  1. JSON to Datatable
  2. Datatable to JSON
  3. JSON to CSV
  4. CSV to JSON
  5. DataTable to CSV
  6. CSV to DataTable
  7. JSON to XLS
  8. Datatable to XLS

Implementation of Data Conversion using Visual Studio

Let's start step-by-step learning using Visual Studio 2022.

  • Open Visual Studio 2022 and create a new project.
    New project
  • Select Console App, give the project name and click on the next button.
    Configure project
  • Select the appropriate.net framework from the dropdown and click on the Create button.
    Console app
  • Once we click on the create button, we will get a new project as below with the program file.
    Code
  • Now right-click on the solution and click on Manage Nuget Packages.
    NuGet Package
  • Search with "SuperConvert" in the search box, select the appropriate stable version, and click the Ok button.
    Search Box
  • Once package installation is done, we will be able to see packages in the project solution under packages as below.
    Package
  • You need to install the required packages "Microsoft.Extensions.Hosting" for configuration.
    Hosting
  • Install "Microsoft.Extensions.DependencyInjection" for dependency injection.
    Dependency Injection
  • Install one more Nuget package, "SuperConvert.Abstraction" for "ISuperConvertExcelService" superConvert inbuilt method to use in your project.
    NuGet Package

Now I will add a code snippet for each data conversion using the SuperConvert Nuget package. Let's start one by one in detail with a code example.

Convert JSON To DataTable

#region Convert Json To DataTable
        // Create Json string 
        var jsonString = "[{\"id\":1,\"firstName\":\"Jay\",\"lastName\":\"Patel\",\"age\":30,\"position\":\"SoftwareEngineer\",\"department\":\"Engineering\"},{\"id\":2,\"firstName\":\"Dev\",\"lastName\":\"Ramani\",\"age\":28,\"position\":\"UXDesigner\",\"department\":\"Design\"},{\"id\":3,\"firstName\":\"Sanket\",\"lastName\":\"Jain\",\"age\":35,\"position\":\"ProjectManager\",\"department\":\"ProjectManagement\"},{\"id\":4,\"firstName\":\"Shudir\",\"lastName\":\"patel\",\"age\":32,\"position\":\"DataScientist\",\"department\":\"DataScience\"},{\"id\":5,\"firstName\":\"Chirag\",\"lastName\":\"soni\",\"age\":27,\"position\":\"MarketingSpecialist\",\"department\":\"Marketing\"}]";

        //Convert json string to DataTable using Super Convert
        DataTable dataTableEmployee = jsonString.ToDataTable();

        // Read DataTable values using foreach
        foreach (DataRow row in dataTableEmployee.Rows)
        {
            foreach (DataColumn column in dataTableEmployee.Columns)
            {
                Console.WriteLine($"\t {column.ColumnName} : {row[column.ColumnName]} \t");
            }
            Console.WriteLine("\n ");
        }

#endregion Convert JSON To DataTable

Convert DataTable to JSON

 #region Convert DataTable to Json
        // Let's convert a datatable to Json format

        string strDataTableToJson = dataTableEmployee.ToJson();

        Console.WriteLine(strDataTableToJson);
 #endregion Convert DataTable to Json

Convert JSON to CSV

#region Convert Json to Csv
      // Let's convert a json to csv format

      var fileName = "JsonToCSV";
      var path = $"C:\\Users\\Jigs\\Desktop\\Article\\SuperConvert";
      string csvPath = strDataTableToJson.ToCsv(path, fileName);
#endregion Convert Json to Csv

Convert CSV to JSON

#region Convert Csv to Json 
   // Let's convert a Csv to Json format
   string csvToJsonString = excelHandler.CsvToJson(csvPath);
#endregion Convert Csv to Json

​​​​​​Convert JSON To XLS

#region Convert Json To Excel
        var xlsFileName = "JsonToExcel";

        var xlsPath = excelHandler.JsonToXls(jsonString, path, xlsFileName + Guid.NewGuid().ToString());
#endregion Json To Excel

Convert DataTable To XLS

#region Convert DataTable To Excel
        var dataTableToxlsFileName = "DataTableToExcel";
        var dataTableToXls = excelHandler.DataTableToXls(dataTableEmployee,path, dataTableToxlsFileName);
#endregion Convert DataTable To Excel

Convert CSV To DataTable

#region Convert CSV To DataTable
        var csvToDataTable = excelHandler.CsvToDataTable(csvPath);

        // Read DataTable values using foreach
        foreach (DataRow row in csvToDataTable.Rows)
        {
            foreach (DataColumn column in csvToDataTable.Columns)
            {
                Console.WriteLine($"\t {column.ColumnName} : {row[column.ColumnName]} \t");
            }
            Console.WriteLine("\n ");
        }
#endregion Convert CSV To DataTable

Output for the above code snippet. I have added only the first screen of the result.

Output

Now I will add all data conversion methods at once to the program file and the dependencies required for "ISuperConvertExcelService" to access the inside program file.

using Microsoft.Extensions.DependencyInjection;
using SuperConvert.Abstraction;
using SuperConvert.Abstraction.Extensions;
using SuperConvert.Extensions;
using System.Data;

internal class Program
{
    private static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
        services.UseSuperConvertExcelService();
        var excelHandler = services.BuildServiceProvider().GetRequiredService<ISuperConvertExcelService>();

        #region Convert Json To DataTable
        // Create Json string 
        var jsonString = "[{\"id\":1,\"firstName\":\"Jay\",\"lastName\":\"Patel\",\"age\":30,\"position\":\"SoftwareEngineer\",\"department\":\"Engineering\"},{\"id\":2,\"firstName\":\"Dev\",\"lastName\":\"Ramani\",\"age\":28,\"position\":\"UXDesigner\",\"department\":\"Design\"},{\"id\":3,\"firstName\":\"Sanket\",\"lastName\":\"Jain\",\"age\":35,\"position\":\"ProjectManager\",\"department\":\"ProjectManagement\"},{\"id\":4,\"firstName\":\"Shudir\",\"lastName\":\"patel\",\"age\":32,\"position\":\"DataScientist\",\"department\":\"DataScience\"},{\"id\":5,\"firstName\":\"Chirag\",\"lastName\":\"soni\",\"age\":27,\"position\":\"MarketingSpecialist\",\"department\":\"Marketing\"}]";

        //Convert json string to DataTable using Super Convert
        DataTable dataTableEmployee = jsonString.ToDataTable();

        // Read DataTable values using foreach
        foreach (DataRow row in dataTableEmployee.Rows)
        {
            foreach (DataColumn column in dataTableEmployee.Columns)
            {
                Console.WriteLine($"\t {column.ColumnName} : {row[column.ColumnName]} \t");
            }
            Console.WriteLine("\n ");
        }

        #endregion Convert Json To DataTable

        #region Convert DataTable to Json
        // Let's convert a datatable to Json format

        string strDataTableToJson = dataTableEmployee.ToJson();

        Console.WriteLine(strDataTableToJson);
        #endregion Convert DataTable to Json

        #region Convert Json to Csv
        // Let's convert a json to csv format

        var fileName = "JsonToCSV";
        var path = $"C:\\Users\\Jigs\\Desktop\\Article\\SuperConvert";
        string csvPath = strDataTableToJson.ToCsv(path, fileName);
        #endregion Convert Json to Csv

        #region Convert Csv to Json 
        // Let's convert a Csv to Json format
        string csvToJsonString = excelHandler.CsvToJson(csvPath);
        #endregion Convert Csv to Json

        #region Convert Json To Excel
        var xlsFileName = "JsonToExcel";

        var xlsPath = excelHandler.JsonToXls(jsonString, path, xlsFileName + Guid.NewGuid().ToString());
        #endregion Json To Excel

        #region  Convert Json To Excel  
        var jsonToxlsFileName = "JsonToExcel";

        var jsonToXls = jsonString.ToXls(path, jsonToxlsFileName);
        #endregion Convert Json To Excel

        #region Convert DataTable To Excel
        var dataTableToxlsFileName = "DataTableToExcel";
        var dataTableToXls = excelHandler.DataTableToXls(dataTableEmployee,path, dataTableToxlsFileName);
        #endregion Convert DataTable To Excel

        #region Convert CSV To DataTable
        var csvToDataTable = excelHandler.CsvToDataTable(csvPath);

        // Read DataTable values using foreach
        foreach (DataRow row in csvToDataTable.Rows)
        {
            foreach (DataColumn column in csvToDataTable.Columns)
            {
                Console.WriteLine($"\t {column.ColumnName} : {row[column.ColumnName]} \t");
            }
            Console.WriteLine("\n ");
        }
        #endregion Convert CSV To DataTable

        Console.ReadLine();
    }
}

Summary

In this article, we have learned how to convert data from one format to another using the SuperConvert Nuget package. It is a powerful Nuget library that provides seamless data conversion in various formats, like JSON to DataTable, DataTable to JSON, JSON to CSV, CSV to JSON, DataTable to CSV, CSV to DataTable, and many more formats.

I have attached the source code in zip format for our example. Please download and leverage this powerful feature in your project to make the data conversion process easy.

Note. I have used Visual Studio 2022 and .Net 6.

Thanks for reading my article. If you wish to read more articles, please refer all article lists here and a few links below.

  1. Export Data In EXCEL, PDF, CSV, Word, JSON, XML, And Text files in .NET Core 3.1 Using MVC Core
  2. Difference Between IQueryable, IEnumerable, And IList In LINQ
  3. Swagger UI Integration With Web API For Testing And Documentation
  4. Implement Lazy Loading In MVC
  5. Create Documentation With Sandcastle Help Builder


Similar Articles