0

I have a datatable like this

ID CategoryID Category
1   1         Category1
2   1         Category2

and I am trying to generate keyed json like this

    {
     "1"
        [
         {Category: Category1},
         {Category:Category2}
        ]
    }

How can I covert my datatable to dictionary<string, list<object>> so that I can serialize it with JSON.NET Yes running in to duplicate key issues with dictionary. Thanks in advance for any ideas.

Usman
  • 4,615
  • 2
  • 17
  • 33
NShaik
  • 13
  • 4
  • datatable structure is not clear in my question so i try again... ID| CategoryID |Category ------------------------------------ 1 | 1 | Category1 2 | 1 | Category2 – NShaik Nov 16 '16 at 07:40
  • Maybe try Json.net http://stackoverflow.com/questions/2979922/how-to-convert-datatable-to-json-string-using-json-net – KMoussa Nov 16 '16 at 08:12

1 Answers1

2

Here full code:

var dataTable = new DataTable();

dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("CategoryID", typeof(int));
dataTable.Columns.Add("Category", typeof(string));

dataTable.Rows.Add(1, 1, "Category1");
dataTable.Rows.Add(2, 1, "Category2");
dataTable.Rows.Add(3, 2, "Category3");
dataTable.Rows.Add(4, 2, "Category4");
dataTable.Rows.Add(5, 1, "Category5");
dataTable.Rows.Add(6, 3, "Category6");


var dict = dataTable.AsEnumerable()
    .GroupBy(row => row.Field<int>("CategoryID"))
    .ToDictionary(
        g => g.Key.ToString(),
        g => g.Select(row => new { Category = row.Field<string>("Category") }).ToList()
    );

var jss = new JavaScriptSerializer();
Console.WriteLine(jss.Serialize(dict));

Last string gives you json (I formatted it for better readability):

{
  "1":
        [
          {"Category":"Category1"},
          {"Category":"Category2"},
          {"Category":"Category5"}
        ],
  "2":
        [
          {"Category":"Category3"},
          {"Category":"Category4"}
        ],
  "3":
        [
          {"Category":"Category6"}
        ]
}
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
  • Thanks! @Alexander Petrov. Worked with absolutely no changes. I kept thinking about grouping but just not bale to complete it....In case any body is looking...to add more columns to the nested object I added them to row separated by comma like this... var dict = dt.AsEnumerable() .GroupBy(row => row.Field("PromotionID")) .ToDictionary(g => g.Key.ToString(), g => g.Select(row => new { DriveID = row.Field("DriveID"), DrieDate=row.Field("DriveDate") }).ToList()); – NShaik Nov 16 '16 at 13:47