从JSON对象填充JTable

Cri*_*ena 1 java rest swing json jtable

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

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在按钮点击事件后将数据加载到该jTable.从JSON键值对,我需要以行方式显示值.

Pau*_*tha 8

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

例如

User

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; }
}
Run Code Online (Sandbox Code Playgroud)

UserTableModelclass - (注意,这是最简单的情况.你可能想添加一些方法来添加行和删除行等.你需要自己添加这些功能.这里有很多好帖子.你可能想要通过@MadProgrammer的个人资料并查看他的abstracttablemodel标记答案或只是查看标签一般).

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mainclass - 使用ObjectMapperJackson 的课程.

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));
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

以下是一些参考资料,您可以访问以获取更多信息:


UPDATE

这是一个在运行时动态添加用户的示例,它使用了addUser方法UserTableModel.键入"用户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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

"它会将员工列表作为JSON数组返回"

如果你有一个JSON数组,你可以很容易地将其转换成一个Java ListObjectMapper.您可以通过一个CollectionType作为第二个参数readValue,通过使用TypeFactory#constructCollectionType.就像是

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述