none
How to generate json a specific way from datatable RRS feed

  • Question

  • i have a .net data table which is populated with sample data but when generating json from datatable then getting json this way

    [{"ID":1,"Name":"Ajay"},{"ID":2,"Name":"Sanu"}]

    my C# code as following

        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(Int32));
        dt.Columns.Add("Name", typeof(string));
    
        DataRow dr = dt.NewRow();
        dr[0] = 1;
        dr[1] = "Ajay";
        dt.Rows.Add(dr);
    
        dr = dt.NewRow();
        dr[0] = 2;
        dr[1] = "Sanu";
        dt.Rows.Add(dr);
    
        var lst = dt.AsEnumerable()
            .Select(r => r.Table.Columns.Cast<DataColumn>()
                    .Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal])
                   ).ToDictionary(z => z.Key, z => z.Value)
            ).ToList();
        //now serialize it
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var m= serializer.Serialize(lst);

     i need to generate json below way from my datatable

    [{  
     "columns": [{  
      "title": "col1_name",  
      "data": "col1_name"  
     }, {  
      "title": "col2_name",  
      "data": "col2_name"  
     }],  
     "data": [{  
      "col1_name": "col1 data",  
      "col2_name": "col2 data"  
     }, {  
      "col1_name": "col1 data",  
      "col2_name": "col2 data"  
     }]  
    }]  

    so please tell me what to change in my code for c# data table and json generation as a result i can generate my json just like above example. please help me with rectified code. thanks

    Monday, December 9, 2019 8:04 PM

All replies

  • Well, you obviously do NOT want JSON exactly like your example, because you don't have columns called "col1_name" and "col2_name".  In fact, that line that you have generated up top is exactly what you should put in the "data" section.  The only question is how to generate the column index, which should presumably look like:

        { "columns": [{"title": "ID", "data": "ID"},{"title":"Name","data":"Name"}]

    You could probably create a class that included a "columns" member and a "data" member that includes your DataTable, but to be honest, it's probably easier to do that as a text string.


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Monday, December 9, 2019 8:20 PM