Asp.net how to convert DataSet to josn and output the datasetjosn
public class JsonUtil { public string ToJson(DataSet dataSet) { string jsonString = "{"; foreach (DataTable table in dataSet.Tables) { jsonString += """" + table.TableName + """:" + ToJson(table) + ","; } jsonString = jsonString.TrimEnd(','); return jsonString + "}"; } public string ToJson(DataTable dt) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { jsonString.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName; string strValue = drc[i][j].ToString(); Type type = dt.Columns[j].DataType; jsonString.Append("""" + strKey + """:"); strValue = String.Format(strValue, type); jsonString.Append("""" + strValue + ""","); } jsonString.Append("},"); } jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } }
Use
JsonUtil ju = new JsonUtil(); Response.Write(ju.ToJson(ds));
If there is a problem with parsing, replace "with" \ "in the code.
How to convert a string to json in aspnet
You can consider converting dataset or a datatable to json, for example, converting the data of a datatable to json:
/// <Summary>
/// Datatable converted to Json
/// </Summary>
/// <Param name = "table"> Datatable object </param>
/// <Returns> Json string </returns>
Public static string ToJson (DataTable dt)
{
StringBuilder jsonString = new StringBuilder ();
If (dt. Rows. Count = 0)
{
JsonString. Append ("[{}]");
Return jsonString. ToString ();
}
JsonString. Append ("[");
DataRowCollection drc = dt. Rows;
For (int I = 0; I <drc. Count; I ++)
{
JsonString. Append ("{");
For (int j = 0; j <dt. Columns. Count; j ++)
{
String strKey = dt. Columns [j]. ColumnName;
String strValue = drc [I] [j]. ToString ();
Type type = dt. Columns [j]. DataType;
JsonString. Append ("\" "+ strKey + "\":");
StrValue = StringFormat (strValue, type );
If (j <dt. Columns. Count-1)
{
JsonString. Append (strValue + ",");
}
Else
{
JsonString. Append (strValue );
}
}
JsonString. Append ("},");
}
JsonString. Remove (jsonString. Length-1, 1 );
JsonString. Append ("]");
Return jsonString. ToString ();
}
How to call the conversion method after dataset converts json data
The front-end can directly process the data in Json format.
Reference: www.ibm.com/..tp3308