On 5/22/2015 4:21 AM, kaushal patel wrote:
> String sql = "select employee_id,first_name,last_name,email,salary from employees";
>
> SqlRowSet employees = null ;
>
> try{
> employees = jdbcTemplate.queryForRowSet(sql);
> }
> catch(Exception e)
> {
> e.printStackTrace();
> }
> return employees ;
>
> I want to know if there is any library present that can convert it to JSON.
>
> I have tried with google GSON Library and Jackson Library but both requires first extraction of column to Type Class like Employee in this case.
It is not hard to code yourself.
Quick attempt:
private static String quoteIfNeeded(Object o) {
if(o instanceof String) {
return "\"" + o.toString() + "\"";
} else if(o instanceof Integer) {
return o.toString();
} else {
throw new IllegalArgumentException(o.getClass().getName() + " not
supported");
}
}
public static String resultSet2JSON(ResultSet rs) throws SQLException {
ArrayList<String> colnams = new ArrayList<>();
ResultSetMetaData rsmd = rs.getMetaData();
for(int i = 0; i < rsmd.getColumnCount(); i++) {
colnams.add(rsmd.getColumnName(i + 1));
}
StringBuilder sb = new StringBuilder();
sb.append("[");
while(rs.next()) {
sb.append("{");
for(int i = 0; i < colnams.size(); i++) {
if(i > 0) {
sb.append(",");
}
sb.append(colnams.get(i));
sb.append(":");
Object o = rs.getObject(i + 1);
sb.append(quoteIfNeeded(o));
}
sb.append("}");
}
sb.append("]");
return sb.toString();
}
Arne