C # Converts a column of a DataTable into a JSON-formatted string

Source: Internet
Author: User

Converts a column of a DataTable into a JSON-formatted string (after conversion, it adds {} to the string before and after it is converted)

// <summary>
///datatable loading and changing column data into JSON's current format
// </summary>
/// <param name= "DT" ></param>
/// <param name= "RowIndex" >datatable the first few lines </param>
// <returns></returns>
protected static string Createtabcolumndatajson (System.Data.DataTable dt, int rowIndex)
{
String jsonstr = "";
DateTime Dtime;
for (int i = 0; i < dt. Columns.count; i++)
{
String cName = dt. Columns[i]. ColumnName;
String cvalue = dt. Rows[rowindex][cname]. ToString ();
if (! String.IsNullOrEmpty (Cvalue)) //! String.IsNullOrEmpty (cvalue) edit by Spark 2011-3-30 F_parcel_term1,f_parcel_term1
{
Try
{
//regex r = new Regex (@ "\d{4}-\d{1,2}-\d{1,2} (\s+\d{1,2}:\d{1,2}:\d{1,2})?");
if (dt. Columns[cname]. DataType = = typeof (DateTime))
//if (R.ismatch (cvalue))
{
Dtime = DateTime.Parse (cvalue);
if (dtime. Hour = = 0 && dtime. Minute = = 0 && dtime. Second = = 0)
{
Cvalue = Dtime. ToString ("Yyyy-mm-dd");
}
Else
{
Cvalue = Dtime. ToString ("Yyyy-mm-dd HH:mm:ss");
}
}
}
catch (Exception ex)
{ }
if (Jsonstr = = "")
Jsonstr = CName + ": '" + cvalue + "'";
Else
Jsonstr + = "," + CName + ":" + cvalue + "'";
}
}
return jsonstr;
}

C # Converts a column of a DataTable into a JSON-formatted string

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.