2

What is the standard/Correct form of the Data Table for the give JSON which has Nested collection?.

JSON FILE

    {
"F1":1,
"F2":2,
"F4":[{"E1":1,"E3":3}]
"F3":[
    {
        "E1":3,
        "E2":4
    },
    {
        "E1":5,
        "E2":6
    },  
    {
        "E1":7,
        "E2":8,
        "E3":[
            {
                "D1":9,
                "D2":10
            }
        ]
    },      
]
}  
Vinod Kumar
  • 408
  • 4
  • 18

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 =
    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 extension method like

 DataTable dt = new DataTable();
 dt = UserList.ToDataTable<User>();

answer is refered by example

Community
  • 1
  • 1
  • Thanks Rajesh.This will work fine if i don't have nested collection in my JSON. but I am asking about the standard format to represent the data in form of DataTable i.e am asking about datatble representation for the above example without any data loss. – Vinod Kumar Feb 05 '16 at 05:57