Skip to content

Instantly share code, notes, and snippets.

@kdonald
Created March 20, 2012 16:35
Show Gist options
  • Save kdonald/2137988 to your computer and use it in GitHub Desktop.
Save kdonald/2137988 to your computer and use it in GitHub Desktop.
Auto Mapping a JDBC ResultSet to JSON
// convenient Spring JDBC RowMapper for when you want the flexibility of Jackson's TreeModel API
// Note: Jackson can also serialize standard Java Collections (Maps and Lists) to JSON: if you don't need JsonNode,
// it's simpler and more portable to have Spring JDBC simply return a Map or List<Map>.
package org.springframework.jdbc.core;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
public class JsonNodeRowMapper implements RowMapper<JsonNode> {
private final ObjectMapper mapper;
public JsonNodeRowMapper(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public JsonNode mapRow(ResultSet rs, int rowNum) throws SQLException {
ObjectNode objectNode = mapper.createObjectNode();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int index = 1; index <= columnCount; index++) {
String column = JdbcUtils.lookupColumnName(rsmd, index);
Object value = rs.getObject(column);
if (value == null) {
objectNode.putNull(column);
} else if (value instanceof Integer) {
objectNode.put(column, (Integer) value);
} else if (value instanceof String) {
objectNode.put(column, (String) value);
} else if (value instanceof Boolean) {
objectNode.put(column, (Boolean) value);
} else if (value instanceof Date) {
objectNode.put(column, ((Date) value).getTime());
} else if (value instanceof Long) {
objectNode.put(column, (Long) value);
} else if (value instanceof Double) {
objectNode.put(column, (Double) value);
} else if (value instanceof Float) {
objectNode.put(column, (Float) value);
} else if (value instanceof BigDecimal) {
objectNode.put(column, (BigDecimal) value);
} else if (value instanceof Byte) {
objectNode.put(column, (Byte) value);
} else if (value instanceof byte[]) {
objectNode.put(column, (byte[]) value);
} else {
throw new IllegalArgumentException("Unmappable object type: " + value.getClass());
}
}
return objectNode;
}
}
@gotomanners
Copy link

Hi there,
What is the purpose of the int rowNum attribute if you don't mind me asking, it seems to be redundant in this snippet?

@steve-taylor
Copy link

It's required to implement RowMapper from Spring JDBC.

@adilek
Copy link

adilek commented Jun 13, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment