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.