Skip to content

Instantly share code, notes, and snippets.

@riaqn
Created April 3, 2015 13:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save riaqn/c0d73996dd187ff0d117 to your computer and use it in GitHub Desktop.
Save riaqn/c0d73996dd187ff0d117 to your computer and use it in GitHub Desktop.
a Gson adapter to convert ResultSet to Json(writer only)
import java.io.*;
import java.sql.*;
import com.google.gson.*;
import com.google.gson.stream.*;
public class ResultSetAdapter extends TypeAdapter<ResultSet> {
public static class NotImplemented extends RuntimeException {}
private static final Gson gson = new Gson();
public ResultSet read(JsonReader reader)
throws IOException {
throw new NotImplemented();
}
public void write(JsonWriter writer, ResultSet rs)
throws IOException {
try {
ResultSetMetaData meta = rs.getMetaData();
int cc = meta.getColumnCount();
writer.beginArray();
while (rs.next()) {
writer.beginObject();
for (int i = 1; i <= cc; ++i) {
writer.name(meta.getColumnName(i));
Class<?> type = Class.forName(meta.getColumnClassName(i));
gson.toJson(rs.getObject(i), type, writer);
//writer.value(rs.getString(i));
}
writer.endObject();
}
writer.endArray();
} catch (SQLException e) {
throw new RuntimeException(e.getClass().getName(), e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getClass().getName(), e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment