java - 从 JSON 对象填充 JTable

标签 java json swing rest jtable

我已经通过访问 MS SQL 数据库成功创建了 REST 服务,我也得到了 JSON 对象, 并且我还在 NetBeans 普通 Java 应用程序中为 REST 客户端创建了 GUI。我想要的不是客户端直接访问数据库并获取数据,而是从接收到的 JSON 对象中填充 JTable。 非常感谢您的帮助。

客户端代码是这样的。这只是为了在控制台中打印它。

public void getJSONEmployees() {
    try {
        Client cl = Client.create();
        WebResource webResource = cl
                .resource("http://localhost:8080/rest_server/rest/jersey/dbAccess/getDBVal");
        ClientResponse response = webResource.accept("application/json")
                .get(ClientResponse.class);

        if (response.getStatus() != 200) {
            System.out.println("no out put");
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

        String output = response.getEntity(String.class);
        // String[] output = response.getEntity(String.);
        System.out.println("\n -------");
        System.out.println(output);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

我想在按钮单击事件后将数据加载到该 jTable 中。 从 JSON 键值对,我需要按行显示的值。

最佳答案

IMO,处理这个问题的最佳方法是使用像 Jackson 这样的库用于 json 到对象的映射(或数据绑定(bind)),只需将 json 对象映射到常规 java 对象。然后只需使用自定义 AbstractTableModel 来保存这些对象的列表。您可以在表模型的 getValueAt() 方法中轻松地将对象属性映射到表列值。

例如

用户

public class User {

    private String firstName;
    private String lastName;

    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public void setFirstName(String firstName) { this.firstName = firstName; }
    public void setLastName(String lastName) { this.lastName = lastName; }
}

UserTableModel - (请注意,这是最简单的情况。您可能需要添加一些方法来添加行和删除行等。您将需要自己添加该功能。SO 上有很多不错的帖子。您可能想浏览@MadProgrammer 的个人资料并查看他的 abstracttablemodel tagged answers 或只查看一般标签)。

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public class UserTableModel extends AbstractTableModel {

    private List<User> userData = new ArrayList<User>();
    private String[] columnNames =  {"First Name", "Last Name"};

    public UserTableModel() {}

    public UserTableModel(List<User> userData) {
        this.userData = userData;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return userData.size();
    }

    @Override
    public Object getValueAt(int row, int column) {
        Object userAttribute = null;
        User userObject = userData.get(row);
        switch(column) {
            case 0: userAttribute = userObject.getFirstName(); break;
            case 1: userAttribute = userObject.getLastName(); break;
            default: break;
        }
        return userAttribute;
    }

    public void addUser(User user) {
        userData.add(user);
        fireTableDataChanged();
    }
}

Main - 使用 ObjectMapper jackson 的课。

import java.awt.Dimension;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MainJsonToObjectDemo {

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                String jsonUser1 = "{ \"firstName\": \"Stack\", \"lastName\": \"Overflow\"}";
                String jsonUser2 = "{ \"firstName\": \"Pee\", \"lastName\": \"Skillet\"}";
                ObjectMapper mapper = new ObjectMapper();
                User user1 = null;
                User user2 = null;
                try {
                    user1 = mapper.readValue(jsonUser1, User.class);
                    user2 = mapper.readValue(jsonUser2, User.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                List<User> users = new ArrayList<User>();
                users.add(user1);
                users.add(user2);
                UserTableModel model = new UserTableModel(users);
                JTable table = new JTable(model) {
                    @Override
                    public Dimension getPreferredScrollableViewportSize() {
                        return new Dimension(300, 100);
                    }
                };
                JOptionPane.showMessageDialog(null, new JScrollPane(table));
            }
        });
    }
}

enter image description here

您可以访问以下引用资料以获取更多信息:

  • > How to use Tables: Creating a Table Model
  • > Jackson Homepage
  • > Jackson wiki with links to tutorials
  • 参见 the GitHub对于 jackson-databind 依赖项。如果您使用 Maven,将其添加为依赖项,也会获取必要的 jackson-corejackson-annotation 依赖项。

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.3.3</version>
    </dependency>
    

    如果您不使用 Maven,请确保您也下载了 jackson-corejackson-annotation。他们每个人都有自己的 GitHub 页面,必须链接到 Maven Central Repo 中的下载。

  • 看看 Rob Camick 的 BeanTableModel .它是通用的 TableModel,允许您从许多业务对象创建表模型,因此您不必经历创建自己的表模型的麻烦。


更新

这是一个在运行时动态添加用户的示例,它使用了 UserTableModeladdUser 方法。输入“用户 json 对象”并点击添加用户

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MainJsonToObjectDemo {

    private JTextArea areaToWriteJson = new JTextArea(6, 30);
    private ObjectMapper objectMapper = new ObjectMapper();
    private JButton addUserButton = getAddUserButton();
    private JTable userTable = getUserTable(300, 150);
    private JFrame frame = new JFrame("Json Objects JTable Demo");

    public MainJsonToObjectDemo() {
        initTableData();
        frame.add(new JScrollPane(areaToWriteJson), BorderLayout.PAGE_START);
        frame.add(addUserButton, BorderLayout.CENTER);
        frame.add(new JScrollPane(userTable), BorderLayout.PAGE_END);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JTable getUserTable(final int width, final int height) {
        UserTableModel model = new UserTableModel();
        JTable table = new JTable(model) {
            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return new Dimension(width, height);
            }
        };
        return table;
    }

    private JButton getAddUserButton() {
        JButton button = new JButton("Add User");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String json = areaToWriteJson.getText();
                if (!json.isEmpty()) {
                    addUser(json);
                }
            }
        });
        return button;
    }

    private void addUser(String jsonString) {
        User user = null;
        try {
            user = objectMapper.readValue(jsonString, User.class);
            ((UserTableModel) userTable.getModel()).addUser(user);
            areaToWriteJson.setText("");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(frame,
                    "Could not map text to User object. Check your formatting: \n"
                    + "{\n"
                    + "    \"firstName\": \"<First>\",\n"
                    + "    \"lastName\": \"<Last>\"\n"
                    + "}", "Error Mapping",
                    JOptionPane.ERROR_MESSAGE);
        }   
    }

    private void initTableData() {
        String jsonUser1 = "{ \"firstName\": \"Stack\", \"lastName\": \"Overflow\"}";
        String jsonUser2 = "{ \"firstName\": \"Pee\", \"lastName\": \"Skillet\"}";
        addUser(jsonUser1);
        addUser(jsonUser2);
    }

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MainJsonToObjectDemo();
            }
        });
    }
}

更新

"there it will return Employee List as a JSON Array"

如果您有一个 json 数组,您可以使用 ObjectMapper 轻松地将其转换为 Java List。您可以使用 TypeFactory#constructCollectionTypeCollectionType 作为第二个参数传递给 readValue .有点像

import java.util.List;
import javax.swing.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class UserListDemo {

    public static void main(String[] args) throws Exception {
        String jsonUsers = 
                 "["
                +  "{ \"firstName\": \"Stack\", \"lastName\": \"Overflow\" },"
                +  "{ \"firstName\": \"Pee\", \"lastName\": \"Skillet\" }" 
                +"]";
        ObjectMapper mapper = new ObjectMapper();
        List<User> users = mapper.readValue(
                jsonUsers,
                TypeFactory.defaultInstance().constructCollectionType(
                        List.class, User.class));
        UserTableModel model = new UserTableModel(users);
        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JOptionPane.showMessageDialog(null, new JScrollPane(table));
    }
}

enter image description here

关于java - 从 JSON 对象填充 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25418029/

相关文章:

java - 没有硬编码值的外观和感觉

java - Webapp文件组织约定(开发结构)

java - JSON Post 请求不包含参数

java - 使用 hasNextLine() 但仍然收到 java.util.NoSuchElementException : No line found

ios - 如何解析响应 xml 字符串?

php - json 列与多列

java - 从 CheckBoxTree 节点中删除复选框

java - 当我为 JFrame 使用 FlowLayout 时,为什么我的图像没有出现?

java - MySQL 中保存的日期无效

java - 用于操作数据库的类,可在 Android 和 Java 桌面上运行