以下代码ResultSet使用JSONArray和将转换为JSON字符串JSONObject。
ResultSet
JSONArray
JSONObject
import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.ResultSetMetaData; public class ResultSetConverter { public static JSONArray convert( ResultSet rs ) throws SQLException, JSONException { JSONArray json = new JSONArray(); ResultSetMetaData rsmd = rs.getMetaData(); while(rs.next()) { int numColumns = rsmd.getColumnCount(); JSONObject obj = new JSONObject(); for (int i=1; i<numColumns+1; i++) { String column_name = rsmd.getColumnName(i); if(rsmd.getColumnType(i)==java.sql.Types.ARRAY){ obj.put(column_name, rs.getArray(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.BIGINT){ obj.put(column_name, rs.getInt(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.BOOLEAN){ obj.put(column_name, rs.getBoolean(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.BLOB){ obj.put(column_name, rs.getBlob(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.DOUBLE){ obj.put(column_name, rs.getDouble(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.FLOAT){ obj.put(column_name, rs.getFloat(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.INTEGER){ obj.put(column_name, rs.getInt(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.NVARCHAR){ obj.put(column_name, rs.getNString(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.VARCHAR){ obj.put(column_name, rs.getString(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.TINYINT){ obj.put(column_name, rs.getInt(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.SMALLINT){ obj.put(column_name, rs.getInt(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.DATE){ obj.put(column_name, rs.getDate(column_name)); } else if(rsmd.getColumnType(i)==java.sql.Types.TIMESTAMP){ obj.put(column_name, rs.getTimestamp(column_name)); } else{ obj.put(column_name, rs.getObject(column_name)); } } json.put(obj); } return json; } }
由于JIT编译器只是分支和基本测试,因此它可能会使其变得非常快。您可以通过对回调进行HashMap查找来使其更加优雅,但我怀疑这样做会更快。至于记忆,这是非常苗条的。
我以某种方式怀疑此代码实际上是内存或性能的关键瓶颈。您有真正的理由尝试对其进行优化吗?