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>
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!