从JSON对象填充JTable [英] Fill JTable from JSON object

查看:131
本文介绍了从JSON对象填充JTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功创建了REST服务并访问了MS SQL数据库,我也获得了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);
抛出新的RuntimeException(失败:HTTP错误代码:
+ response.getStatus());
}

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

} catch(例外e){
e.printStackTrace();
}
}

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

解决方案

IMO,处理此问题的最佳方法是使用像

  • 杰克逊主页

  • 杰克逊wiki及其教程链接

  • 请参阅 GitHub jackson-databind 依赖项。如果您正在使用maven,请将其添加为依赖项,将获取必要的 jackson-core jackson-annotation 依赖性也。

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

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




  • 看看Rob Camick的< a href =http://tips4java.wordpress.com/2008/11/27/bean-table-model/ =nofollow noreferrer> BeanTableModel 。它是通用的 TableModel ,它允许您从许多业务对象创建表模型,因此您不必经历创建自己的业务对象的麻烦。







  • 更新



    这是一个在运行时动态添加用户的示例,利用 UserTableModel <的 addUser 方法/ code>。输入用户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;

    公共类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);
    }
    };
    返回表;
    }

    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);
    }
    }
    });
    返回按钮;
    }

    private void addUser(String jsonString){
    User user = null;
    try {
    user = objectMapper.readValue(jsonString,User.class);
    ((UserTableModel)userTable.getModel())。addUser(user);
    areaToWriteJson.setText();
    } catch(异常e){
    JOptionPane.showMessageDialog(frame,
    无法将文本映射到User对象。检查格式:\ n
    +{\\ \\ n
    +\firstName \:\< First> \,\ n
    +\lastName \:\< ;上次> \\ n
    +},错误映射,
    JOptionPane.ERROR_MESSAGE);
    }
    }

    private void initTableData(){
    String jsonUser1 ={\firstName \:\Stack \,\\ \\lastName \:\Overflow \};
    字符串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();
    }
    });
    }
    }






    更新


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


    如果你有一个json数组,你可以使用<$ c $轻松地将它转换为Java List C> ObjectMapper 。您可以使用 CollectionType 作为第二个参数传递给 readValue jackson.codehaus.org/1.8.8/javadoc/org/codehaus/jackson/map/type/TypeFactory.html#constructCollectionType%28java.lang.Class,%20java.lang.Class%29rel =nofollow noreferrer> 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();
    列表<用户> 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));
    }
    }


    I have created the REST service successfully with accessing to the MS SQL database, and I am getting the JSON object as well, and also I have created the GUI for REST client in NetBeans normal java Application. Rather than client accessing to database and fetching data directly, what I want is to fill the JTable from the received JSON object. Your help really appreciate.

    client code is this. this is just to print it in console.

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

    I want to load data in to that jTable after the button click event. From JSON key value pair, values i need to display in row wise.

    解决方案

    IMO, the best way to handle this is to use a library like Jackson for json-to-object-mapping (or data binding) and just map your json objects to a regular java object. Then just use a custom AbstractTableModel to hold a list of the those object. You can easily map the object attributes to table column values in the getValueAt() method of your table model..

    For example

    User class

    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 class - (Note, this is the simplest of cases. You may want to add some methods to add rows and remove rows and such. You will need to add that functionality your self. There are many good posts here on SO. You may want to go through @MadProgrammer's profile and check out his abstracttablemodel tagged answers or just check out the tag in general).

    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 class - which uses the ObjectMapper class from 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));
                }
            });
        }
    }
    

    Here are some references you can go to for more information:

    • How to use Tables: Creating a Table Model
    • Jackson Homepage
    • Jackson wiki with links to tutorials
    • See the GitHub for the jackson-databind dependency. If you're using maven, add this as a dependency, will grab the necessary jackson-core and jackson-annotation dependencies also.

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

      If you aren't using maven, make sure you download the jackson-core and jackson-annotation also. They each have their own GitHub page that has to link to the download in the Maven Central Repo.

    • Have a look at Rob Camick's BeanTableModel. It's generic TableModel that will allow you to create a table model from many of your business objects, so you don't have to go through the hassle of creating your own.


    UPDATE

    Here is an example that adds user dynamically at run time, making use of the addUser method of the UserTableModel. Type in a "User json object" and hit Add User

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


    UPDATE

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

    If you have a json array, you can easily convert that to a Java List with the ObjectMapper. You can pass a CollectionType as the second argument to the readValue, by using TypeFactory#constructCollectionType. Something like

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

    这篇关于从JSON对象填充JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆