{"id":76499,"date":"2022-11-01T07:00:54","date_gmt":"2022-11-01T06:00:54","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=76499"},"modified":"2022-11-02T08:21:13","modified_gmt":"2022-11-02T07:21:13","slug":"convert-datatable-json-csharp","status":"publish","type":"post","link":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/","title":{"rendered":"How to Convert DataTable to JSON in C#"},"content":{"rendered":"<p>Converting DataTable to JSON is one of those tasks that we come across from time to time and it seems like there should be a built-in method to do it. Unfortunately, that is not the case and we need to figure out a way to do it on our own.<\/p>\n<p>In this article, we will examine different ways to accomplish this and compare the performances of each proposed method.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/csharp-intermediate-topics\/DataTableToJson\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s dive in.<\/p>\n<h2>Serialize a DataTable Using Newtonsoft.Json Package<\/h2>\n<p>We will start with the method that is easiest to implement.<\/p>\n<p><a href=\"https:\/\/www.nuget.org\/packages\/Newtonsoft.Json\/\" target=\"_blank\" rel=\"nofollow noopener\">JSON.NET<\/a> library supports <a href=\"https:\/\/code-maze.com\/serialization-deserialization-csharp\/\" target=\"_blank\" rel=\"noopener\">serialization and deserialization<\/a> of <code>DataTable<\/code> out-of-the-box.\u00a0<\/p>\n<p>So, we can implement a method that takes advantage of this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string DataTableNewtonsoftJsonNet(DataTable dataTable)\r\n{\r\n    if (dataTable == null)\r\n    {\r\n        return string.Empty;\r\n    }\r\n\r\n    return Newtonsoft.Json.JsonConvert.SerializeObject(dataTable);\r\n}<\/pre>\n<p>We can see it is pretty straightforward to convert <code>DataTable<\/code> to JSON using the <code>JsonConvert<\/code> class which is defined in the <code>Newtonsoft.Json<\/code> namespace.<\/p>\n<h2>Serialize a DataTable Using System.Text.Json<\/h2>\n<p>Unlike JSON.NET, the native <code>System.Text.Json<\/code> library does not support <code>DataTable<\/code> conversion out-of-the-box.\u00a0<\/p>\n<p>We can still make use of it with a small workaround:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string DataTableSystemTextJson(DataTable dataTable)\r\n{\r\n    if (dataTable == null)\r\n    {\r\n        return string.Empty;\r\n    }\r\n\r\n    var data = dataTable.Rows.OfType&lt;DataRow&gt;()\r\n                .Select(row =&gt; dataTable.Columns.OfType&lt;DataColumn&gt;()\r\n                    .ToDictionary(col =&gt; col.ColumnName, c =&gt; row[c]));\r\n\r\n    return System.Text.Json.JsonSerializer.Serialize(data);\r\n}<\/pre>\n<p>Although <code>DataTable<\/code> serialization is not supported, with a bit of the LINQ magic, we can convert <code>DataTable<\/code> to a list of <code>KeyValue<\/code> objects.\u00a0<\/p>\n<p>Now we can use <code>JsonSerializer<\/code> on this new structure to get the resulting JSON string.<\/p>\n<h2>Construct JSON String<\/h2>\n<p>Let&#8217;s examine a more &#8220;manual&#8221; approach to this problem that revolves around the idea of composing a JSON string on our own.<\/p>\n<p>For this, we will define two methods. The first one uses <code>StringBuilder<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string DataTableStringBuilder(DataTable dataTable)\r\n{\r\n    if (dataTable == null)\r\n    {\r\n        return string.Empty;\r\n    }\r\n\r\n    var jsonStringBuilder = new StringBuilder();\r\n    if (dataTable.Rows.Count &gt; 0)\r\n    {\r\n        jsonStringBuilder.Append(\"[\");\r\n        for (int i = 0; i &lt; dataTable.Rows.Count; i++)\r\n        {\r\n            jsonStringBuilder.Append(\"{\");\r\n            for (int j = 0; j &lt; dataTable.Columns.Count; j++)\r\n                jsonStringBuilder.AppendFormat(\"\\\"{0}\\\":\\\"{1}\\\"{2}\",\r\n                        dataTable.Columns[j].ColumnName.ToString(),\r\n                        dataTable.Rows[i][j].ToString(),\r\n                        j &lt; dataTable.Columns.Count - 1 ? \",\" : string.Empty);\r\n\r\n            jsonStringBuilder.Append(i == dataTable.Rows.Count - 1 ? \"}\" : \"},\");\r\n        }\r\n        jsonStringBuilder.Append(\"]\");\r\n    }\r\n\r\n    return jsonStringBuilder.ToString();\r\n}<\/pre>\n<p>The second method uses LINQ to construct the result we need:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string DataTableLinq(DataTable dataTable)\r\n{\r\n    if (dataTable == null)\r\n    {\r\n        return string.Empty;\r\n    }\r\n\r\n    return \"[\" \r\n            + string.Join(\",\", dataTable.Rows.OfType&lt;DataRow&gt;()\r\n            .Select(row =&gt;\r\n                \"{\" \r\n                + string.Join(\",\", dataTable.Columns.OfType&lt;DataColumn&gt;()\r\n                    .Select(col =&gt; string.Format(\"\\\"{0}\\\":\\\"{1}\\\"\", \r\n                                        col.ColumnName, \r\n                                        row[col].ToString())))\r\n                + \"}\"))\r\n            + \"]\";\r\n}<\/pre>\n<p>These two methods can be useful when we have a <code>DataTable<\/code> with a simpler, well-defined structure. If the structure is complicated, it is not revised to use this kind of &#8220;manual&#8221; approach.<\/p>\n<h2>Performance Tests<\/h2>\n<p>Let&#8217;s now compare how these methods perform by running benchmark tests.<\/p>\n<p>First, we will define our test entity Student:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Student\r\n{\r\n    public string FirstName { get; set; } = string.Empty;\r\n    public string LastName { get; set; } = string.Empty;\r\n    public int BirthYear { get; set; }\r\n}<\/pre>\n<p>We will generate a test <code>DataTable<\/code> using the\u00a0<a href=\"https:\/\/github.com\/bchavez\/Bogus\" target=\"_blank\" rel=\"nofollow noopener\">Bogus<\/a> library which will be covered in one of our future articles.<\/p>\n<p>To perform tests\u00a0we will define a class <code>Benchmark<\/code> that contains <code>GenerateDummyDataTable<\/code> which generates our test data:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private readonly Faker&lt;Student&gt; _faker = new Faker&lt;Student&gt;();\r\n\r\n...\r\n\r\npublic DataTable GenerateDummyDataTable(int count = 1000)\r\n{\r\n    var dt = new DataTable();\r\n    dt.Columns.Add(\"FirstName\");\r\n    dt.Columns.Add(\"LastName\");\r\n    dt.Columns.Add(\"BirthYear\");\r\n\r\n    foreach (var item in _faker\r\n        .RuleFor(m =&gt; m.FirstName, faker =&gt; faker.Person.FirstName)\r\n        .RuleFor(m =&gt; m.LastName, faker =&gt; faker.Person.LastName)\r\n        .RuleFor(m =&gt; m.BirthYear, faker =&gt; faker.Person.DateOfBirth.Year)\r\n        .Generate(count))\r\n        dt.Rows.Add(new object[] { item.FirstName, item.LastName, item.BirthYear });\r\n    \r\n    return dt;\r\n}\r\n<\/pre>\n<p>Now we can create the methods we will use to perform benchmarking:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[Benchmark]\r\npublic void NewtonsoftJsonNet() =&gt; Methods.DataTableNewtonsoftJsonNet(dataTable);\r\n\r\n[Benchmark]\r\npublic void SystemTextJson() =&gt; Methods.DataTableSystemTextJson(dataTable);\r\n\r\n[Benchmark]\r\npublic void Linq() =&gt; Methods.DataTableLinq(dataTable);\r\n\r\n[Benchmark]\r\npublic void StringBuilder() =&gt; Methods.DataTableStringBuilder(dataTable);<\/pre>\n<p>Since we want to test our methods against a <code>DataTable<\/code> of different sizes, we will define additional classes that inherit the main <code>Benchmark<\/code> class but generate test data of different sizes:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Benchmark_10000 : Benchmark\r\n{\r\n    public Benchmark_10000()\r\n    {\r\n        dataTable = GenerateDummyDataTable(10000);\r\n    }\r\n}\r\n\r\npublic class Benchmark_100000 : Benchmark\r\n{\r\n    public Benchmark_100000()\r\n    {\r\n        dataTable = GenerateDummyDataTable(100000);\r\n    }\r\n}\r\n\r\npublic class Benchmark_1000000 : Benchmark\r\n{\r\n    public Benchmark_1000000()\r\n    {\r\n        dataTable = GenerateDummyDataTable(1000000);\r\n    }\r\n}\r\n<\/pre>\n<p>Finally, we are ready to run the tests.<\/p>\n<p>First, let&#8217;s see the performance on a <code>DataTable<\/code> with 1,000 records:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">|            Method |     Mean |    Error |   StdDev |   Median | Rank | Allocated |\r\n|------------------ |---------:|---------:|---------:|---------:|-----:|----------:|\r\n| NewtonsoftJsonNet | 504.1 us |  3.71 us |  3.28 us | 503.6 us |    1 | 295.92 KB |\r\n|     StringBuilder | 550.2 us |  2.75 us |  2.58 us | 550.2 us |    2 | 248.55 KB |\r\n|    SystemTextJson | 852.1 us | 16.39 us | 20.73 us | 849.8 us |    3 |  521.1 KB |\r\n|              Linq | 965.4 us | 18.55 us | 15.49 us | 960.5 us |    4 | 958.85 KB |<\/pre>\n<p>Let&#8217;s now see how the methods perform on a <code>DataTable<\/code> with 10,000 records:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">|            Method |      Mean |     Error |    StdDev |    Median | Rank | Allocated |\r\n|------------------ |----------:|----------:|----------:|----------:|-----:|----------:|\r\n| NewtonsoftJsonNet |  5.342 ms | 0.0802 ms | 0.1014 ms |  5.332 ms |    1 |   2.84 MB |\r\n|     StringBuilder |  6.499 ms | 0.1107 ms | 0.1036 ms |  6.488 ms |    2 |   2.39 MB |\r\n|    SystemTextJson |  9.996 ms | 0.1406 ms | 0.1315 ms |  9.979 ms |    3 |   5.08 MB |\r\n|              Linq | 10.072 ms | 0.0806 ms | 0.0715 ms | 10.046 ms |    3 |   9.36 MB |<\/pre>\n<p>What about 100,000 records:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">|            Method |     Mean |    Error |   StdDev |   Median | Rank | Allocated |\r\n|------------------ |---------:|---------:|---------:|---------:|-----:|----------:|\r\n| NewtonsoftJsonNet | 65.73 ms | 1.279 ms | 1.522 ms | 65.75 ms |    1 |   28.4 MB |\r\n|              Linq | 69.30 ms | 1.181 ms | 1.105 ms | 69.59 ms |    2 |  93.57 MB |\r\n|     StringBuilder | 79.16 ms | 1.457 ms | 1.363 ms | 78.85 ms |    3 |  23.82 MB |\r\n|    SystemTextJson | 82.51 ms | 1.227 ms | 1.088 ms | 82.92 ms |    4 |  50.81 MB |<\/pre>\n<p>And finally, let&#8217;s see the performance on 1,000,000 records:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">|            Method |     Mean |    Error |   StdDev |   Median | Rank | Allocated |\r\n|------------------ |---------:|---------:|---------:|---------:|-----:|----------:|\r\n| NewtonsoftJsonNet | 616.1 ms |  5.41 ms |  4.79 ms | 614.1 ms |    1 | 283.89 MB |\r\n|              Linq | 670.7 ms | 12.74 ms | 12.51 ms | 668.1 ms |    2 | 935.59 MB |\r\n|    SystemTextJson | 798.0 ms | 11.91 ms | 10.56 ms | 793.3 ms |    3 | 508.04 MB |\r\n|     StringBuilder | 915.7 ms |  4.27 ms |  3.57 ms | 914.9 ms |    4 | 238.14 MB |<\/pre>\n<p>As we can see, besides simplicity, JSON.NET also has the best performance, both in terms of speed and memory usage, in all examples. Based on this, we can conclude it is the best choice for this task.<\/p>\n<p>A bit surprisingly, the performance we get from the <code>StringBuilder<\/code> method is only slightly worse. The speed drops as the data size increases, but the memory usage is even better than we get with JSON.NET.\u00a0<\/p>\n<p>LINQ method shows better timings as the size of the data increases but it uses the most memory in all examples.\u00a0<\/p>\n<p>And in the end, a bit of a mediocre performance of the <code>System.Text.Json<\/code> method puts it in last place.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we learned about different methods to convert DataTable to JSON and investigated how these methods perform on example data of different sizes.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Converting DataTable to JSON is one of those tasks that we come across from time to time and it seems like there should be a built-in method to do it. Unfortunately, that is not the case and we need to figure out a way to do it on our own. In this article, we will [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[232,1478,927,544,1157,928,1158],"class_list":["post-76499","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-conversion","tag-datatable","tag-json","tag-linq","tag-newtonsoft-json","tag-serialization","tag-system-text-json","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Convert DataTable to JSON in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"There&#039;s no in-built method to convert a DataTable to JSON so let&#039;s explore different ways we can do that ourselves.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Convert DataTable to JSON in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"There&#039;s no in-built method to convert a DataTable to JSON so let&#039;s explore different ways we can do that ourselves.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-11-01T06:00:54+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-02T07:21:13+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Convert DataTable to JSON in C#\",\"datePublished\":\"2022-11-01T06:00:54+00:00\",\"dateModified\":\"2022-11-02T07:21:13+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/\"},\"wordCount\":572,\"commentCount\":5,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"Conversion\",\"DataTable\",\"JSON\",\"LINQ\",\"Newtonsoft.Json\",\"Serialization\",\"System.Text.Json\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/\",\"url\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/\",\"name\":\"How to Convert DataTable to JSON in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-11-01T06:00:54+00:00\",\"dateModified\":\"2022-11-02T07:21:13+00:00\",\"description\":\"There's no in-built method to convert a DataTable to JSON so let's explore different ways we can do that ourselves.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Convert DataTable to JSON in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Convert DataTable to JSON in C# - Code Maze","description":"There's no in-built method to convert a DataTable to JSON so let's explore different ways we can do that ourselves.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/","og_locale":"en_US","og_type":"article","og_title":"How to Convert DataTable to JSON in C# - Code Maze","og_description":"There's no in-built method to convert a DataTable to JSON so let's explore different ways we can do that ourselves.","og_url":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/","og_site_name":"Code Maze","article_published_time":"2022-11-01T06:00:54+00:00","article_modified_time":"2022-11-02T07:21:13+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Convert DataTable to JSON in C#","datePublished":"2022-11-01T06:00:54+00:00","dateModified":"2022-11-02T07:21:13+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/"},"wordCount":572,"commentCount":5,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["Conversion","DataTable","JSON","LINQ","Newtonsoft.Json","Serialization","System.Text.Json"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/convert-datatable-json-csharp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/","url":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/","name":"How to Convert DataTable to JSON in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-11-01T06:00:54+00:00","dateModified":"2022-11-02T07:21:13+00:00","description":"There's no in-built method to convert a DataTable to JSON so let's explore different ways we can do that ourselves.","breadcrumb":{"@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/convert-datatable-json-csharp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/convert-datatable-json-csharp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Convert DataTable to JSON in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/76499","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=76499"}],"version-history":[{"count":9,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/76499\/revisions"}],"predecessor-version":[{"id":76547,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/76499\/revisions\/76547"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=76499"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=76499"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=76499"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}