Home > Backend Development > C++ > How to Convert JSON to a DataTable in C# using Newtonsoft.Json?

How to Convert JSON to a DataTable in C# using Newtonsoft.Json?

Linda Hamilton
Release: 2025-01-26 20:46:10
Original
521 people have browsed it

How to Convert JSON to a DataTable in C# using Newtonsoft.Json?

Efficiently Converting JSON to a DataTable in C# with Newtonsoft.Json

This guide demonstrates a streamlined method for transforming JSON data into a DataTable using the powerful Newtonsoft.Json library in C#. This approach avoids the need for intermediate custom C# classes, simplifying the conversion process.

Here's the code implementation:

<code class="language-csharp">using Newtonsoft.Json;

// Example JSON data
string jsonData = "[{\"id\":\"10\",\"name\":\"User\",\"add\":false,\"edit\":true,\"authorize\":true,\"view\":true},{\"id\":\"11\",\"name\":\"Group\",\"add\":true,\"edit\":false,\"authorize\":false,\"view\":true},{\"id\":\"12\",\"name\":\"Permission\",\"add\":true,\"edit\":true,\"authorize\":true,\"view\":true}]";

// Direct JSON to DataTable conversion
DataTable dataTable = (DataTable)JsonConvert.DeserializeObject(jsonData, typeof(DataTable));

// Displaying the DataTable contents
Console.WriteLine("---------------------------------------------------------------------");
Console.WriteLine("ID    |  Name     |  Add    |   Edit  | View   | Authorize");
Console.WriteLine("---------------------------------------------------------------------");
foreach (DataRow row in dataTable.Rows)
{
    Console.WriteLine($"{row["id"]}    | {row["name"]}    | {row["add"]}    | {row["edit"]}  | {row["view"]}   |  {row["authorize"]}");
}</code>
Copy after login

Newtonsoft's JsonConvert.DeserializeObject method directly handles the deserialization, specifying typeof(DataTable) as the target type. This makes the code concise and efficient. After conversion, standard DataTable methods allow for easy data manipulation and access.

The above is the detailed content of How to Convert JSON to a DataTable in C# using Newtonsoft.Json?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template