java通过结果集ResutSet来拼接json数据格式

项目需要,参考了一些网上的方法,修修补补适合自己的项目用的,小计一下。

public class JsonUtil {

	/**
	 * 
	 * @param rs
	 *            数据结果集
	 * @param jsonResult     
         * {result:[ {colName:value,colName1:value2}]}
         * 
	 *	{result:[
	 *     	{id:0,data:["","value2","value1"]}]}       
         *     json result
	 * @param type
	 * @return
	 */
	public static String GetJsonByResultSet(ResultSet rs, String jsonResult,
			int type) {
		ResultSetMetaData rsmd = null;
		StringBuffer sb = null;
		try {
			rsmd = rs.getMetaData();
			if (rs == null || rsmd.getColumnCount() < 0) {
				return "{\"ok\":false}";
			}
			sb = new StringBuffer();
			sb = sb.append("{" + jsonResult + ":[");
			int i = 0;
			while (rs.next()) {
				if (i == 0) {
					sb.append("{");
				} else {
					sb.append(",{");
				}
				if (type == 0) {
					sb.append("id:" + i++ + ",data:[\"\"");
				} else {
					i++;
				}
				int count = rsmd.getColumnCount();
				for (int j = 0; j < count; j++) {
					int type_i = rsmd.getColumnType(j + 1);
					String colName = rsmd.getColumnName(j + 1);
					String colValue = noNull(rs.getString(j + 1));
					switch (type_i) {
					case Types.VARCHAR:
						sb.append(changCharacter(type, colName, j)+ colValue+ "\"");
						break;
					case Types.CHAR:
						sb.append(changCharacter(type, colName, j)+ colValue + "\"");
						break;
					case Types.INTEGER:
						sb.append(changCharacter(type, colName, j)+ colValue + "\"");
						break;
					case Types.TIMESTAMP:
						sb.append(changCharacter(type, colName, j)+ colValue + "\"");
						break;
					case Types.NUMERIC:
						if ((rsmd.getPrecision(j + 1)) == 0) {
							sb.append(changCharacter(type, colName, j)+ rs.getLong(j + 1) + "\"");
						} else {
							DecimalFormat df = new DecimalFormat("######0.00");
							double num = rs.getDouble(j + 1);
							String numStr = df.format(num);
							sb.append(changCharacter(type, colName, j) + numStr+ "\"");
						}
						break;
					case Types.DATE:
						sb.append(changCharacter(type, colName, j)+ colValue + "\"");
						break;
					default:
					}
				}
				if (type == 0) {
					sb.append("]}");
				} else {
					sb.append("}");
				}

			}
			sb.append("]}");

		} catch (SQLException ex) {
		}
		return sb.toString();
	}

	/**
	 * 处理字符串,如果为null,转变为"",否则不转变
	 */
	public static String noNull(Object src) {
		if (src == null) {
			src = "";
		}
		return src.toString();
	}
	private static String changCharacter(int type, String colName, int number) {
		String st = null;
		if (type == 0) {
			st = ",\"";
		} else {
			if (number == 0) {
				st = colName + ":\"";
			} else {
				st = "," + colName + ":\"";
			}
		}
		return st;
	}
}

 方法是直接可以用的

返回的数据格式然后后一篇讲怎么通过json-lib 来解析

你可能感兴趣的:(java,json,J#)