There are now a lot of JSON-related Java tools, such as Json-lib, Gson, and so on, which can convert javabean directly into JSON format.
In development, it is possible to get data from the database and want to go directly to the JSON array, not through the bean.
For example, perform the following conversions:
Data sheet:
Id
Name
Age
1
Xxg
23
2
Xiaoming
20
Convert to JSON array:
[
{
"id": "1",
"name": "Xxg",
"Age": "All"
},
{
"id": "2",
"name": "Xiaoming",
"Age": "
" }
]
The implementation is simple, that is, the query results resultset every piece of data into a JSON object, the column name and value of each column in the data form a key-value pair, placed in the object, and finally organized into a JSON array.
[Java] view Plaincopyprint?
- Public String Resultsettojson (ResultSet rs) throws Sqlexception,jsonexception
- {
- JSON array
- Jsonarray array = new Jsonarray ();
- Get Number of columns
- ResultSetMetaData metaData = Rs.getmetadata ();
- int columnCount = Metadata.getcolumncount ();
- Traverse each piece of data in the ResultSet
- while (Rs.next ()) {
- Jsonobject jsonobj = new Jsonobject ();
- Iterate through 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 ();
- }
Public String Resultsettojson (ResultSet rs) throws Sqlexception,jsonexception { //JSON array jsonarray array = new Jsonarray (); Gets the number of columns resultsetmetadata metaData = Rs.getmetadata (); int columnCount = Metadata.getcolumncount (); Traverse each data 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 Org.json jar package, which can be downloaded anywhere on the web.
Fork Brother reproduced please indicate the source: http://blog.csdn.net/xiao__gui/article/details/8612503
Java database resultset to JSON implementation