モデルのデータを反復処理し、jacksonを使用してjsonを生成できます。すなわち:
public static JsonNode getJsonNodeFromModel(DefaultTableModel model) {
ArrayNode jsonArray = MAPPER.createArrayNode();
for (int i = 0; i < model.getRowCount(); i++) {
ObjectNode jsonNode = MAPPER.createObjectNode();
String name = (String) model.getValueAt(i, 0);
String command = ((String) model.getValueAt(i, 1)).replace("\\", "\\\\");
jsonNode.put(model.getColumnName(0), name);
jsonNode.put(model.getColumnName(1), command);
jsonArray.add(jsonNode);
}
return jsonArray;
}
テスト:
@Test
public void testMethod() {
Object[] columnNames = new Object[]{"Name", "Shell Command"};
Object[][] data = {
{"Open jsonlint.com", "open http://jsonlint.com"},
{"Open Escape/UnEscape Tool", "open http://www.freeformatter.com/javascript-escape.html"}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JsonNode jsonNode = CommandHelper.getJsonNodeFromModel(model);
assertEquals("Open jsonlint.com", jsonNode.get(0).get("Name").asText());
assertEquals("open http://jsonlint.com", jsonNode.get(0).get("Shell Command").asText());
assertEquals("Open Escape/UnEscape Tool", jsonNode.get(1).get("Name").asText());
assertEquals("open http://www.freeformatter.com/javascript-escape.html", jsonNode.get(1).get("Shell Command").asText());
}