Convert DataSet to json, and DataSet to json
/// <Summary>
/// Convert dataset data to json format
/// </Summary>
/// <Param name = "ds"> dataset </param>
/// <Returns> json string </returns>
Public static string GetJsonByDataset (DataSet ds)
{
If (ds = null | ds. Tables. Count <= 0 | ds. Tables [0]. Rows. Count <= 0)
{
// If the queried data is null, mark OK: false
Return "{\" OK \ ": false }";
}
StringBuilder sb = new StringBuilder ();
Sb. Append ("{\" OK \ ": true ,");
Foreach (DataTable dt in ds. Tables)
{
Sb. Append (string. Format ("\" {0} \ ": [", dt. TableName ));
Foreach (DataRow dr in dt. Rows)
{
Sb. Append ("{");
For (int I = 0; I <dr. Table. Columns. Count; I ++)
{
Sb. appendFormat ("\" {0} \ ": \" {1} \ ",", dr. table. columns [I]. columnName. replace ("\"","\\\""). replace ("\ '", "\'"), ObjToStr (dr [I]). replace ("\"","\\\""). replace ("\'","\\\'")). replace (Convert. toString (char) 13), "\ r \ n "). replace (Convert. toString (char) 10), "\ r \ n ");
}
Sb. Remove (sb. ToString (). LastIndexOf (','), 1 );
Sb. Append ("},");
}
Sb. Remove (sb. ToString (). LastIndexOf (','), 1 );
Sb. Append ("],");
}
Sb. Remove (sb. ToString (). LastIndexOf (','), 1 );
Sb. Append ("}");
Return sb. ToString ();
}
/// <Summary>
/// Convert an object to a string
/// </Summary>
/// <Param name = "ob"> obj object </param>
/// <Returns> </returns>
Public static string ObjToStr (object ob)
{
If (ob = null)
{
Return string. Empty;
}
Else
Return ob. ToString ();
} Ajax call post-processing $. getJSON ("page. aspx", {process: 'getinfo', idx: idx}, function (json ){
If (json. OK = true ){
$ ("# SlGameType"). val (json. Table [0]. GameType );
$ ("# TxtSelectName"). val (json. Table [0]. SelectName );
$ ("# TxtmyName"). val (json. Table1 [0]. myName );
$ ("# Txtmyinfo"). val (json. Table1 [0]. info );
}
});