【问题标题】:Java Sorting Tabular Data and Output to JSON?Java对表格数据进行排序并输出到JSON?
【发布时间】:2018-04-23 12:59:11
【问题描述】:

图片 Excel 数据、行和列,能够对任何列进行 ASC 或 DESC 排序。

我希望在 Java 中复制此功能,然后将数据输出到 JSON - 此 JSON 数据被放置在一个 API 中,可以查询并返回基于特定列名排序的表格样式数据。

最好的方法是什么?

JTable 看起来像 可能 帮助,https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting,尽管我目前不确定如何将这些过滤到 JSON 对象的数据映射。

有什么建议/想法吗?

【问题讨论】:

    标签: 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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      相关资源
      最近更新 更多