U kunt de Gson van Google gebruiken in dit geval:
public String getJSONFromResultSet(ResultSet rs, String key) {
Map json = new HashMap();
List list = new ArrayList();
if (rs != null) {
try {
ResultSetMetaData mData = rs.getMetaData();
while (rs.next()) {
Map<String, Object> columns = new HashMap<String, Object>();
for (int columnIndex = 1; columnIndex <= mData.getColumnCount(); columnIndex++) {
if (rs.getString(mData.getColumnName(columnIndex)) != null) {
columns.put(mData.getColumnLabel(columnIndex),
rs.getString(mData.getColumnName(columnIndex)));
} else {
columns.put(mData.getColumnLabel(columnIndex), "");
}
}
list.add(columns);
}
} catch (SQLException e) {
e.printStackTrace();
}
json.put(key, list);
}
return new Gson().toJson(json);
}
Bijwerken: U kunt getJSONFromResultSet
. aanroepen methode zoals hieronder:
Connection con = DBConnectionClass.myConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM Customer");
//as an example consider a table named Customer in your DB.
ResultSet rs = ps.executeQuery();
System.out.println(getJSONFromResultSet(rs, "customer"));