1

I want to convert a DataTable to nested JSON. I have a table Announcement with column name Category, Headline, Details, Short_desc, Author and Display_date.

Datatabel result is like:

Category     Headline    Details     Short_desc  Author   Display_date 

Sports       H1          d1          sd1          a1        dd1
Sports       h2          d2          sd2          a2        dd2
Technology   t1          d3          sd3          a3        dd3
Technology   t2          d4          sd4          a4        dd4

Now I want JSON result something like:

{   
  "Sports" : [ [ 
        "Headline":"H1",
        "Details":"d1",
        "Short_desc":"sd1",
        "Author":"a1",
        "Display_date":"dd1"
      ],
      [ "Headline":"H2",
        "Details":"d2",
        "Short_desc":"sd2",
        "Author":"a2",
        "Display_date":"dd2"
      ]
    ],
  "Technology" : [ [ 
        "Headline":"t1",
        "Details":"d3",
        "Short_desc":"sd3",
        "Author":"a3",
        "Display_date":"dd3"
      ],
      [ "Headline":"t4",
        "Details":"d4",
        "Short_desc":"sd4",
        "Author":"a4",
        "Display_date":"dd4"
      ]
    ]
}

I used the following code:

DataTable dts = get_banner_detail_service("");

System.Web.Script.Serialization.JavaScriptSerializer serializer = 
    new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dts.Rows)
{
    row = new Dictionary<string, object>();
    foreach (DataColumn col in dts.Columns)
    {
        row.Add(col.ColumnName, dr[col]);
    }
    rows.Add(row);
}
Response.Write(serializer.Serialize(rows));
Response.Flush();
Response.End();

Result of above code is not like what I expected. It is like:

   {   
      "Sports" : [ 
            "Headline":"H1",
            "Details":"d1",
            "Short_desc":"sd1",
            "Author":"a1",
            "Display_date":"dd1"
          ],
       "Sports" :[ 
            "Headline":"H2",
            "Details":"d2",
            "Short_desc":"sd2",
            "Author":"a2",
            "Display_date":"dd2"
          ] ....
        }
2
  • What is the problem? Can you explain? Does it crash? Or is the output not like expected? Commented Feb 26, 2014 at 6:58
  • Yes output is not like that which i really wants . it returns category wise result Commented Feb 26, 2014 at 7:05

3 Answers 3

1

You need to create nested dictionary as:

        Dictionary<string, Dictionary<string, object>> rows = new Dictionary<string, Dictionary<string, object>>();
        Dictionary<string, object> row;
        foreach (DataRow dr in dts.Rows)
        {
            row = new Dictionary<string, object>();
            var columns = dts.Columns;

            for (int i = 1; i < columns.Count; i++)
            {
                row.Add(columns[i].ColumnName, dr[columns[i]]);
            }

            if (rows.ContainsKey(columns[0].ColumnName))
                rows[columns[0].ColumnName] = rows[columns[0].ColumnName].Concat(row).ToDictionary(p=>p.Key,v=>v.Value);
            else
                rows[columns[0].ColumnName] = row;

        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply but Argument Exception occur-An item with the same key has already been added.
1

HI Finally i solve the issue ... below is the updated code -

DataTable dts = get_banner_detail_service("");
        DataTable dtc = get_banner_detail_cat("");
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> rowss;
        Dictionary<string, object> rowsc;
        List<object> rowsin;
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        rowsc = new Dictionary<string, object>();
        foreach (DataRow dr in dtc.Rows)
        {
            string cat = dr["Category"].ToString();

            var filteredAndroid = (from n in dts.AsEnumerable()
                                   where n.Field<string>("Category").Contains(cat)
                                   select n).ToList();

            if (filteredAndroid.Count != 0)
            {
                DataTable t = filteredAndroid.CopyToDataTable();

                t.Columns.Remove("Category");
                rowss = new Dictionary<string, object>();

                rowsin = new List<object>();
                foreach (DataRow drr in t.Rows)
                {
                    foreach (DataColumn col in t.Columns)
                    {
                        rowss.Add(col.ColumnName, drr[col]);
                    }
                    rowsin.Add(rowss);
                    rowss = new Dictionary<string, object>();

                }
                rowsc.Add(cat, rowsin);
                t.Dispose();
                t = null;
                filteredAndroid = null;
            }
        }
        rows.Add(rowsc);

        string json = JsonConvert.SerializeObject(rows, Newtonsoft.Json.Formatting.Indented);
        if (json.Length > 2)
        {
            json = json.Substring(1, json.Length - 2);
        }
        Response.Write(json);
        Response.Flush();
        Response.End();

Comments

0

Nested Json tree with linq

      var structured =  from grp in QueryResult.GroupBy(x => x.col1)
                 select new
                 {   name = grp.Key,
                     newgrp = from af in grp.GroupBy(y => y.col2)
                                  select new
                                  {   name = af.Key,
                                      case_id =sy.Max(c=>c.col_nameId)}
                                  }
                   }                
                 };

1 Comment

Answer needs supporting information Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.