Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi This is I Get Data how to i convert to list or DataTable Following Json Result.

What I have tried:

C#
{"AuditPrm": [
  {
    "AuditId": 1,
    "AuditId": 7,
    "Remarks": "Test Cond",
    "UserId": 4
  },
  {
    "AuditId": 2,
    "AuditId": 7,
    "Remarks": "Test Cond",
    "UserId": 4
  }
]}


dynamic dynObj = JsonConvert.DeserializeObject(obj.ToString());
<pre> Audit empObj = JsonConvert.DeserializeObject<Audit>(dynObj); 

Posted
Updated 13-Oct-16 4:07am

1 solution

You can use json2csharp.com to Convert your json to an object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Click on Generate.
  • You will get C# Code for your object model
  • Deserialize by

    C#
    using NewtonJson;
    ...
    var model = JsonConvert.DeserializeObject



Here's a method to convert a list to a databale:

C#
public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}
 
Share this answer
 
v3
Comments
Dinesh92d 13-Oct-16 10:22am    
that will be ok but i need to list or Datatable. How can i used it
#realJSOP 13-Oct-16 11:49am    
Well, I suppose you would convert the deserialized data to a datatable. I updated my answer to include a method I found using google (google access is free, you should try it).
Richard Deeming 13-Oct-16 12:34pm    
If you're using a recent version of Visual Studio (2012.2 or later), you don't even need an external site. Just use Edit ⇒ Paste Special ⇒ Paste JSON As Classes:
‘Paste JSON As Classes’ in ASP.NET and Web Tools 2012.2 RC[^]

(If it doesn't show up, make sure you've got a reference to JSON.NET in your project.)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900