将JDBC ResultSet解析为JSON格式

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

JSON建构于两种结构:

  • “名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
  • 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

在Java中使用json,除了通过javabean等一些方法外,还可以直接操作ResultSet。

实现ResultSet接口后,可以将其转化为常见对象,如json,list,map,数组等等。这里只实现了ResultSet –> json.


1.实现ResultSetHandler接口

public interface RsHandler {/*** Turn the ResultSet into an Object.** @param rs 要操作的数据集* @return 返回特定格式的resultset对象* @throws SQLException 数据库异常*/T handle(ResultSet rs) throws SQLException;
}

2.定义一个JSONHandler处理ResultSet接口

public class JsonHandler implements RsHandler<JSONArray>{} 
实现这个接口
    @Overridepublic JSONArray handle(ResultSet rs) throws SQLException {//创建一个JSONArray对象JSONArray jsonArray = new JSONArray();//获得ResultSetMeataData对象ResultSetMetaData rsmd = rs.getMetaData();while (rs.next()) {//定义json对象JSONObject obj = new JSONObject();//判断数据类型&获取valuegetType(rs, rsmd, obj);//将对象添加到JSONArray中jsonArray.put(obj);}return jsonArray;}
根据数据类型获取数据
private void getType(ResultSet rs, ResultSetMetaData rsmd,JSONObject obj) throws SQLException {int total_rows = rsmd.getColumnCount();for (int i = 0; i < total_rows; i++) {String columnName = rsmd.getColumnLabel(i + 1);if (obj.has(columnName)) {columnName += "1";}try {switch (rsmd.getColumnType(i + 1)) {case java.sql.Types.ARRAY:obj.put(columnName, rs.getArray(columnName));break;case java.sql.Types.BIGINT:obj.put(columnName, rs.getInt(columnName));break;case java.sql.Types.BOOLEAN:obj.put(columnName, rs.getBoolean(columnName));break;case java.sql.Types.BLOB:obj.put(columnName, rs.getBlob(columnName));break;case java.sql.Types.DOUBLE:obj.put(columnName, rs.getDouble(columnName));break;case java.sql.Types.FLOAT:obj.put(columnName, rs.getFloat(columnName));break;case java.sql.Types.INTEGER:obj.put(columnName, rs.getInt(columnName));break;case java.sql.Types.NVARCHAR:obj.put(columnName, rs.getNString(columnName));break;case java.sql.Types.VARCHAR:obj.put(columnName, rs.getString(columnName));break;case java.sql.Types.TINYINT:obj.put(columnName, rs.getInt(columnName));break;case java.sql.Types.SMALLINT:obj.put(columnName, rs.getInt(columnName));break;case java.sql.Types.DATE:obj.put(columnName, rs.getDate(columnName));break;case java.sql.Types.TIMESTAMP:obj.put(columnName, rs.getTimestamp(columnName));break;default:obj.put(columnName, rs.getObject(columnName));break;}} catch (JSONException e) {e.printStackTrace();}}}

数据表:
这里写图片描述

解析结果:

[{"mymoney": "100","name": "aa","id": 1},{"mymoney": "20","name": "bb","id": 2},{"mymoney": "50","name": "cc","id": 3}
]


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部