简体   繁体   中英

Java Sorting Tabular Data and Output to JSON?

Picture Excel data, rows and columns, with the ability to sort either for ASC or DESC on any column.

I'm looking to replicate this functionality within Java then output the data into JSON - This JSON data is being placed within an API that can be queried and return tabular style data which is sorted based on a specific column name.

What is the best approach to this?

JTable seems to look like it may help, https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting , although I'm currently unsure how to then map this data that is filtered into a JSON object.

Any pointers / thoughts?

See my example below. I have used GSON dependency shown below to convert a Vector to a JSON string. And I have used JTable.convertRowIndexToModel() API to get table rows in correct order.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM