Created
April 3, 2015 13:20
-
-
Save riaqn/c0d73996dd187ff0d117 to your computer and use it in GitHub Desktop.
a Gson adapter to convert ResultSet to Json(writer only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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