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でどのように解析するかについて説明します.