public class GsonUtil {json
public static JsonArray forJsonUtil(ResultSet rs) { JsonArray jsonArray = new JsonArray(); try { ResultSetMetaData md = rs.getMetaData(); int num = md.getColumnCount(); JsonObject jsonObject = new JsonObject(); while (rs.next()) { for (int i = 1; i <= num; i++) { Object o = rs.getObject(i); if (o instanceof Date) { jsonObject.addProperty(md.getColumnName(i), DateUtil.formatDate((Date) o, "yyyy-MM-dd")); } else if (o instanceof Integer) { jsonObject.addProperty(md.getColumnName(i), (Integer) rs.getObject(i)); } else if (o instanceof Double) { jsonObject.addProperty(md.getColumnName(i), (Double) rs.getObject(i)); } else { jsonObject.addProperty(md.getColumnName(i), (String) rs.getObject(i)); } } jsonArray.add(jsonObject); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonArray; } public static JSONObject forJsonObjectUtil(ResultSet rs) { JSONObject jsonObject = new JSONObject(); try { ResultSetMetaData md = rs.getMetaData(); int num = md.getColumnCount(); while (rs.next()) { for (int i = 1; i <= num; i++) { Object o = rs.getObject(i); if (o instanceof Date) { jsonObject.put(md.getColumnName(i), DateUtil.formatDate((Date) o, "yyyy-MM-dd")); } else { jsonObject.put(md.getColumnName(i), rs.getObject(i)); } } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject; }
兩者主要的區別在 Gson與JSON在使用ResultSetMetaData時的區別在於Gson須要指明欄位的類型,否則存在轉換異常的問題code