Convert DataSet to json, and DataSet to json

Source: Internet
Author: User

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 );
}
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.