-3
{
  "data": [
        {
            "sheetname": "Sheet1",
            "datas": [
                {
                    "cloumn1": "6986",
                    "cloumn2": "1",
                    "cloumn3": "Server01"
                }
            ]
        },
        {
            "sheetname": "Sheet2",
            "datas": [
                {
                    "cloumn1": "6986",
                    "cloumn2": "1",
                    "cloumn3": "Server01"
                },
                {
                    "cloumn1": "6986",
                    "cloumn2": "1",
                    "cloumn3": "Server01"
                }
            ]
        }
    ]
}

How to convert this json into datatable?
Condition:

  1. Every item in "Data" attribute should be in different tab.(in above example there are 2 items so 2 worksheets should be created)
  2. If "datas" attaribute contain 1 object --->1 row in 1 sheet
  3. If "datas" attaribute contain 2 object --->2 rows in 1 sheet
Steven
  • 1,996
  • 3
  • 22
  • 33
priyanka gharat
  • 25
  • 1
  • 2
  • 10

1 Answers1

1

Deserialize your jsonstring to some class

List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);

Write following extension method to your project

public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TpeDescriptor.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 extension method like

UserList.ToDataTable<User>();

This code is taken from here: Convert JSON to DataTable