Vinod Kumar
Vinod Kumar

Reputation: 408

Nested JSON to DataTable Standard Format

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
            }
        ]
    },      
]
}  

Upvotes: 2

Views: 1897

Answers (1)

Kutty Rajesh Valangai
Kutty Rajesh Valangai

Reputation: 635

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

Upvotes: 1

Related Questions