Implementation of converting Java Database resultset to JSON

Source: Internet
Author: User

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

 
  1. Public String resultsettojson (resultset RS) throws sqlexception, jsonexception
  2. {
  3. // JSON Array
  4. Jsonarray array = new jsonarray ();
  5. // Obtain the number of Columns
  6. Resultsetmetadata metadata = Rs. getmetadata ();
  7. Int columncount = metadata. getcolumncount ();
  8. // Traverse each data entry in the resultset
  9. While (Rs. Next ()){
  10. Jsonobject jsonobj = new jsonobject ();
  11. // Traverse each column
  12. For (INT I = 1; I <= columncount; I ++ ){
  13. String columnname = metadata. getcolumnlabel (I );
  14. String value = Rs. getstring (columnname );
  15. Jsonobj. Put (columnname, value );
  16. }
  17. Array. Put (jsonobj );
  18. }
  19. Return array. tostring ();
  20. }

 

 

The above Code only needs to use the jar package of org. JSON, which can be downloaded anywhere on the Internet.

 

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.