Converting DataSet to JSON is not working in asp.net

瘦欲@ 提交于 2019-12-24 23:50:58

问题


I am bring data in many Table so I want it to convert it to json while returning it. So I tried like below

public static string DataSetToJSON(DataSet dset)
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
        Dictionary<string, object> childRow;
        foreach (DataRow row in dset.Rows)
        {
            childRow = new Dictionary<string, object>();
            foreach (DataColumn col in dset.Columns)
            {
                childRow.Add(col.ColumnName, row[col]);
            }
            parentRow.Add(childRow);
        }
        return jsSerializer.Serialize(parentRow);
    }

But I am getting error at dset.Rows

System.data.dataset does not contain a definition for Rows....


回答1:


Dataset is a collection of data tables. The rows would exist in a datatable. So you need to check the datatable in the dataset and then loop through existing columns and rows.

Try getting the first datable:

DataTable firstTable = dset.Tables[0]; 

If there are many data tables, then you need to loop the datatables as:

foreach(DataTable dt in dset.Tables)
{
  //then you can get the rows and columns values for each table as above
   foreach (DataRow row in dt.Rows)
   {
       childRow = new Dictionary<string, object>();
       foreach (DataColumn col in dt.Columns)
       {
          childRow.Add(col.ColumnName, row[col]);
       }
       parentRow.Add(childRow);
   }
}



回答2:


After checking and doing some research and also on the guidance of SLAKS I finally did it.

public static string DataSetToJSON(DataSet ds)
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
        Dictionary<string, object> childRow;

        foreach (DataTable table in ds.Tables)
        {
            foreach (DataRow dr in table.Rows)
            {
                childRow = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                {
                    childRow.Add(col.ColumnName, dr[col]);
                }
                parentRow.Add(childRow);
            }
        }

        return jsSerializer.Serialize(parentRow);
    }

Thanks SLAKS



来源:https://stackoverflow.com/questions/49258534/converting-dataset-to-json-is-not-working-in-asp-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!