Language: English

Archive for May, 2016

Convert JSON to DataTable

JSON in the following format –

<br />
[<br />
    {&quot;id&quot;:&quot;10&quot;,&quot;name&quot;:&quot;User&quot;,&quot;add&quot;:false,&quot;edit&quot;:true,&quot;authorize&quot;:true,&quot;view&quot;:true},<br />
    {&quot;id&quot;:&quot;11&quot;,&quot;name&quot;:&quot;Group&quot;,&quot;add&quot;:true,&quot;edit&quot;:false,&quot;authorize&quot;:false,&quot;view&quot;:true},<br />
    {&quot;id&quot;:&quot;12&quot;,&quot;name&quot;:&quot;Permission&quot;,&quot;add&quot;:true,&quot;edit&quot;:true,&quot;authorize&quot;:true,&quot;view&quot;:true}<br />
]<br />

Need to convert that into a C# DataTable object as follows :-

<br />
---------------------------------------------------------------------<br />
ID    |  Name     |  Add    |   Edit  | View   | Authorize<br />
---------------------------------------------------------------------<br />
10    | User      | true    |  true   | true   |  true<br />
11    | Group     | true    |  true   | true   |  true<br />
12    | Permission| true    |  true   | true   |  true<br />

Deserialize your jsonstring to some class –


List UserList = JsonConvert.DeserializeObject>(jsonString);

Write following extension method to your project –

<br />
public static DataTable ToDataTable&lt;T&gt;(this IList&lt;T&gt; data)<br />
{<br />
    PropertyDescriptorCollection props =<br />
    TypeDescriptor.GetProperties(typeof(T));<br />
    DataTable table = new DataTable();<br />
    for(int i = 0 ; i &lt; props.Count ; i++)<br />
    {<br />
    PropertyDescriptor prop = props[i];<br />
    table.Columns.Add(prop.Name, prop.PropertyType);<br />
    }<br />
    object[] values = new object[props.Count];<br />
    foreach (T item in data)<br />
    {<br />
    for (int i = 0; i &lt; values.Length; i++)<br />
    {<br />
        values[i] = props[i].GetValue(item);<br />
    }<br />
    table.Rows.Add(values);<br />
    }<br />
    return table;<br />
}<br />

Call extension method like

<br />
UserList.ToDataTable&lt;User&gt;();<br />




Categories
Links: