public class JsonUtil {
public static JSONArray formatRsToJsonArray(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData();
int num = md.getColumnCount();
JSONArray array = new JSONArray(); while(rs.next()){
JSONObject mapOfColValues = new JSONObject();for(int i = 1;i<=num;i++){Object o = rs.getObject(i);if(o instanceof Date){mapOfColValues.put(md.getColumnName(i), DateUtil.formatDateToString((Date)o, "yyyy-MM-dd"));}else{mapOfColValues.put(md.getColumnName(i),
rs.getObject(i));}}array.add(mapOfColValues);}return array;}}
public class DateUtil {
public static String formatDateToString(Date date,String format){
String result = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
if(date != null){
result=sdf.format(date);
}
return result;
}
public static Date formatStringToDate(String str,String format) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(str);
}
}
结果集转JSON
本文介绍了一种将数据库查询结果集转换为JSON格式的方法。通过遍历结果集的元数据并逐行读取数据,将其封装成JSON对象,最终形成一个包含所有记录的JSON数组。此外,还提供了一个日期格式化的辅助方法以确保日期类型的字段能正确地被格式化为字符串形式。
954

被折叠的 条评论
为什么被折叠?



