python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 7, Interview Questions Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
3 Best Ways To Convert JSON to DataTable in Asp.net C#

3 Best Ways To Convert JSON to DataTable in ASP.Net C#

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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions