Skip to content

Instantly share code, notes, and snippets.

@nfisher
Last active September 20, 2018 23:33
Show Gist options
  • Save nfisher/5f81fef20d6175144d1d81b6f32c41bc to your computer and use it in GitHub Desktop.
Save nfisher/5f81fef20d6175144d1d81b6f32c41bc to your computer and use it in GitHub Desktop.
POJO to BigQuery TableRow converter
class DataToRow {
public static TableRow asRow(final Object child, final String pkg) {
if (null == child) {
return null;
}
TableRow row = new TableRow();
Field[] publicFields = child.getClass().getFields();
for (Field f : publicFields) {
String name = f.getName();
try {
Object v = f.get(child);
String type = f.getType().getCanonicalName();
if (type.startsWith("java.lang.") || type.startsWith("java.util.")) {
row.set(name, v);
} else if (type.startsWith(pkg)) {
// recurse, what could possibly go wrong.
row.set(name, asRow(v, pkg));
} else {
// TODO: decide what to do when an unknown type.
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return row;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment