Http://blog.csdn.net/xiao__gui/article/details/8612503
There are many JSON-related Java tools, such as JSON-lib and gson. They can directly convert Javabean to JSON format.
During development, data may be retrieved from the database and directly converted into a JSON array without passing beans.
For example, perform the following conversion:
Data Table:
ID |
Name |
Age |
1 |
XxG |
23 |
2 |
Xiaoming |
20 |
Convert to a JSON array:
[
{
"ID": "1 ",
"Name": "xxG ",
"Age": "23"
},
{
"ID": "2 ",
"Name": "Xiaoming ",
"Age": "20"
}
]
The implementation is very simple, that is, converting each piece of data in the resultset of the query result into a JSON object. The column names and values of each column in the data form a key-Value Pair and place it in the object, finally, the object is organized into a JSON array.
[Java]View plaincopy
- Public String resultsettojson (resultset RS) throws sqlexception, jsonexception
- {
- // JSON Array
- Jsonarray array = new jsonarray ();
- // Obtain the number of Columns
- Resultsetmetadata metadata = Rs. getmetadata ();
- Int columncount = metadata. getcolumncount ();
- // Traverse each data entry in the resultset
- While (Rs. Next ()){
- Jsonobject jsonobj = new jsonobject ();
- // Traverse each column
- For (INT I = 1; I <= columncount; I ++ ){
- String columnname = metadata. getcolumnlabel (I );
- String value = Rs. getstring (columnname );
- Jsonobj. Put (columnname, value );
- }
- Array. Put (jsonobj );
- }
- Return array. tostring ();
- }
The above Code only needs to use the jar package of org. JSON, which can be downloaded anywhere on the Internet.