将JTable转换为JSON

时间:2018-05-25 19:30:26

标签: java json jtable

我有这种方法从DefaultTableModel获取数据并使用JSONArray库将其转换为org.json

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
    }
}

奇怪的是,根据JTable所拥有的数据,此方法的结果是正确的。例如,像这样的表:

+----+------------------+
| id | role_description |
+----+------------------+
|  1 | admin            |
|  2 | user             |
+----+------------------+

将成功转换为:

[{"id":"1","role_description":"admin"},{"id":"2","role_description":"user"}]

但是有一个日期的表格,例如:

+----------+------------------+------------+---------------------+
| 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 |
+----------+------------------+------------+---------------------+

将转换为:

[{"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"}]

我不知道为什么订单错了。

注意:列的for从1开始的原因是因为第一列是为行号保留的,我不想在JSON中包含这些列。

0 个答案:

没有答案