How can I convert JSON to DataTable into a C#?
How to perform serialization and deserialization of DataTable to and from JSON?
What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight data interchange format. It is a text format that is completely language independent. It is very easy to read and write.
This JSON is used for converting as DataTable and this JSON string after finishing desterilizing object.
{ "Result":[ {"IsEnabled": true,"Id": 10015,"Name": "Reena"}, {"IsEnabled": true,"Id": 10016,"Name": "Anil Singh"}, {"IsEnabled": false,"Id": 10017,"Name": "Aradhya","__metadata": { "Id": 14013 }} ] }
Method 1-
Convert JSON to DataTable and we can achieved using below code with the help of “Newtonsoft.Json”.
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Data; using System.Linq; public static DataTable ConvertJsonToDatatable(string jsonString) { var jsonLinq = JObject.Parse(jsonString); // Find the first array using Linq var linqArray = jsonLinq.Descendants().Where(x => x is JArray).First(); var jsonArray = new JArray(); foreach (JObject row in linqArray.Children<JObject>()) { var createRow = new JObject(); foreach (JProperty column in row.Properties()) { // Only include JValue types if (column.Value is JValue) { createRow.Add(column.Name, column.Value); } } jsonArray.Add(createRow); } return JsonConvert.DeserializeObject<DataTable>(jsonArray.ToString()); }
Method 2-
using System.Runtime.Serialization; using System.Runtime.Serialization.Json; public static string Serialize<T>(T obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, obj); string retVal = Encoding.UTF8.GetString(ms.ToArray()); return retVal; } public static T Deserialize<T>(string json) { T obj = Activator.CreateInstance<T>(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); ms.Close(); return obj; }
Method 3-
//De-serialize your json string to your class.
List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonStr);
//Write an extension method as,
public static DataTable ToDataTable<T>(this IList<T> data) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); DataTable table = new DataTable(); for(int i = 0 ; i < props.Count ; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } object[] values = new object[props.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } return table; }
//Call your extension method as,
users.ToDataTable<User>();
I hope you are enjoying with this post! Please share with you friends. Thank you!!