Function for converting a self-written able into a JSON string

Source: Internet
Author: User

JSON data has been used recently, and the datatable must be converted to JSON. Previously, newtonsoft. JSON. dll was used for serialization. First, the datatable should be converted into XML format, and then newtonsoft. JSON. dll should be used to convert XML format to JSON format. (See previousArticleHttp://blog.csdn.net/luq885/archive/2007/05/10/1603330.aspx)

In fact, the JSON data format is relatively simple. After careful research, we found that it is not very complicated to directly break down the able and then construct it into the JSON format using stringbuilder. FunctionCodeAs follows:

Private   String Datatable2json (datatable DT)
... {
Stringbuilder jsonbuilder =   New Stringbuilder ();
Jsonbuilder. append ( " {\" " );
Jsonbuilder. append (Dt. tablename );
Jsonbuilder. append ( "\ ":[ " );
For ( Int I =   0 ; I < DT. Rows. Count; I ++ )
... {
Jsonbuilder. append ( " { " );
For ( Int J =   0 ; J < DT. Columns. Count; j ++ )
... {
Jsonbuilder. append ( "\ " " );
Jsonbuilder. append (Dt. Columns [J]. columnname );
Jsonbuilder. append ( "\ ":\" " );
Jsonbuilder. append (Dt. Rows [I] [J]. tostring ());
Jsonbuilder. append ( "\ ", " );
}
Jsonbuilder. Remove (jsonbuilder. Length -   1 , 1 );
Jsonbuilder. append ( " }, " );
}
Jsonbuilder. Remove (jsonbuilder. Length -   1 , 1 );
Jsonbuilder. append ( " ] " );
Jsonbuilder. append ( " } " );
Return Jsonbuilder. tostring ();
}

This line "jsonbuilder. remove (jsonbuilder. length-1, 1); "is to remove more than the last comma. Of course, this function cannot operate datatable that contains complex data types, but it is enough for the current work.

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.