I have this method that takes data from a DefaultTableModel
and converts it to a JSONArray
using org.json
library.
public static void writeTableToFileAsJSON(JTable table, String filePath) {
table.setColumnSelectionInterval(1, table.getColumnCount() - 1);
table.setRowSelectionInterval(0, table.getRowCount() - 1);
DefaultTableModel model = (DefaultTableModel) table.getModel();
int rowCount = model.getRowCount();
int columnCount = model.getColumnCount();
boolean firstRow = true;
try (FileWriter fw = new FileWriter(filePath)) {
fw.write("[");
for (int i = 0; i < rowCount; i++) {
JSONObject jsonObj = new JSONObject();
for (int j = 1; j < columnCount; j++) {
Object value = model.getValueAt(i, j);
String columnName = model.getColumnName(j);
System.out.println(value + " - " + columnName);
jsonObj.put(columnName, value);
}
fw.write(firstRow ? jsonObj.toString() : ("," + jsonObj.toString()));
firstRow = false;
}
fw.write("]");
} catch (IOException | JSONException e) {
//TODO handle ex
}
}
What's strange is that depending on the data the JTable holds, the result from this method is correct. For example, a table like this:
+----+------------------+
| id | role_description |
+----+------------------+
| 1 | admin |
| 2 | user |
+----+------------------+
Will be successfully converted to:
[{"id":"1","role_description":"admin"},{"id":"2","role_description":"user"}]
But a table that has dates, for example:
+----------+------------------+------------+---------------------+
| store_id | manager_staff_id | address_id | last_update |
+----------+------------------+------------+---------------------+
| 1 | 1 | 1 | 2006-02-15 04:57:12 |
| 2 | 2 | 2 | 2006-02-15 04:57:12 |
+----------+------------------+------------+---------------------+
Will be converted to:
[{"store_id":"1","manager_staff_id":"1","last_update":"2006-02-15 04:57:12","address_id":"1"},{"store_id":"2","manager_staff_id":"2","last_update":"2006-02-15 04:57:12","address_id":"2"}]
And I have no idea why the order is wrong.
Note: the reason why the for
for columns starts at 1 is because the first column is reserved for row numbers and I don't want to include those in the JSON.