Converting DataSet to JSON is not working in asp.n

2019-08-29 19:07发布

问题:

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



标签: c# json dataset