ResultSet 到 JSON 的最高效轉換?
以下程式碼使用JSON 陣列和物件將結果集轉換為JSON 字串:
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); // Determine the SQL data type of the column switch(rsmd.getColumnType(i)) { case java.sql.Types.ARRAY: obj.put(column_name, rs.getArray(column_name)); break; case java.sql.Types.BIGINT: obj.put(column_name, rs.getInt(column_name)); break; case java.sql.Types.BOOLEAN: obj.put(column_name, rs.getBoolean(column_name)); break; case java.sql.Types.BLOB: obj.put(column_name, rs.getBlob(column_name)); break; case java.sql.Types.DOUBLE: obj.put(column_name, rs.getDouble(column_name)); break; case java.sql.Types.FLOAT: obj.put(column_name, rs.getFloat(column_name)); break; case java.sql.Types.INTEGER: obj.put(column_name, rs.getInt(column_name)); break; case java.sql.Types.NVARCHAR: obj.put(column_name, rs.getNString(column_name)); break; case java.sql.Types.VARCHAR: obj.put(column_name, rs.getString(column_name)); break; case java.sql.Types.TINYINT: obj.put(column_name, rs.getInt(column_name)); break; case java.sql.Types.SMALLINT: obj.put(column_name, rs.getInt(column_name)); break; case java.sql.Types.DATE: obj.put(column_name, rs.getDate(column_name)); break; case java.sql.Types.TIMESTAMP: obj.put(column_name, rs.getTimestamp(column_name)); break; default: obj.put(column_name, rs.getObject(column_name)); break; } } json.put(obj); } return json; } }
替代方案解決方案:
替代方案解決方案: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; i++) { String column_name = rsmd.getColumnName(i); obj.put(column_name, rs.getObject(column_name)); } json.put(obj); } return json;另一種方法可能更簡單且更節省內存,直接使用getObject()方法:
以上是在 Java 中將 ResultSet 轉換為 JSON 最有效的方法是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!