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.

2
  • datatable structure is not clear in my question so i try again... ID| CategoryID |Category ------------------------------------ 1 | 1 | Category1 2 | 1 | Category2 Commented Nov 16, 2016 at 7:40
  • Maybe try Json.net stackoverflow.com/questions/2979922/… Commented Nov 16, 2016 at 8:12

1 Answer 1

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"}
        ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

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<Guid>("PromotionID")) .ToDictionary(g => g.Key.ToString(), g => g.Select(row => new { DriveID = row.Field<int>("DriveID"), DrieDate=row.Field<DateTime>("DriveDate") }).ToList());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.