【问题标题】:Java Sorting Tabular Data and Output to JSON?Java对表格数据进行排序并输出到JSON?
【发布时间】:2018-04-23 12:59:11
【问题描述】:
【问题讨论】:
标签:
java
sorting
jtable
columnsorting
gridview-sorting
【解决方案1】:
请参阅下面的示例。我使用了如下所示的 GSON 依赖项将 Vector 转换为 JSON 字符串。我已经使用 JTable.convertRowIndexToModel() API 以正确的顺序获取表行。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
public class TableDataToJson {
public static void main(String[] args) {
JFrame frame = new JFrame("Table data to JSON");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DefaultTableModel tableModel = new DefaultTableModel(
new Object[][] {{"Sugar", 14}, {"Eggs", 8}, {"Butter", 12}, {"Flour", 10}},
new Object[] {"Item name", "Price"}) {
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 1) {
return Integer.class;
}
return super.getColumnClass(columnIndex);
}
};
final JTable table = new JTable(tableModel);
table.setAutoCreateRowSorter(true);
JButton button = new JButton("Print JSON");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Vector vectorInModelOrder = tableModel.getDataVector();
Vector vectorInViewOrder = new Vector();
for (int i = 0; i < vectorInModelOrder.size(); i++) {
vectorInViewOrder.add(vectorInModelOrder.get(table.convertRowIndexToModel(i)));
}
Gson gson = new Gson();
System.out.println(gson.toJson(vectorInViewOrder));
}
});
frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}