Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Can we convert a Java ResultSet/SqlRowSet from Database query directly to JSON array without Mapping it to a List<Type>?

905 views
Skip to first unread message

kaushal patel

unread,
May 22, 2015, 4:21:45 AM5/22/15
to
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.

If I am able to do this it can provide me a dynamic nature on my frontend like once we have 3 columns on frontend then we want 4 u just have to edit the query.

Arne Vajhøj

unread,
May 22, 2015, 9:15:35 PM5/22/15
to
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

0 new messages