在JTable Java中显示JSONArray

时间:2018-08-03 07:32:00

标签: java json jtable

我有一个JSONArray,需要插入到JTable中,但是根据我的搜索,我得出的结论是,将JSONArray插入到{{ 1}},将其转换为JTable,然后我可以使用JSONObject将其插入JTable

我设法将ArrayList转换为JSONArray,如下所示,但是当我尝试将其转换为JSONObject并将其插入到{ Arraylist。你能告诉我怎么做吗?有没有更简单的方法将JTable插入JSONArray

JSONArray:

JTable

JSONObject:

[{"FOODID":"Jus Alpukat","PRICE":"7000","NUM":"1","RES":"7000.0","ORDERID_FK":""},{"FOODID":"Ice Cream","PRICE":"5000","NUM":"10","RES":"50000.0","ORDERID_FK":""}]

从JSONArray到JSONObject的转换程序:

 {"RES":"7000.0","PRICE":"7000","NUM":"1","FOODID":"Jus Alpukat","ORDERID_FK":""}
 {"RES":"50000.0","PRICE":"5000","NUM":"10","FOODID":"Ice Cream","ORDERID_FK":""}

1 个答案:

答案 0 :(得分:1)

JTable可以将Vector<Vector<String>>用作简单的表模型。因此,如果您只需要显示值,则可以使用以下相当简单的方法:

    JSONArray jsonArr = new JSONArray(lineRead);
    Vector<Vector<String>> dataList = new Vector<>();
    for (int i = 0; i < jsonArr.length(); i++) {

        JSONObject jsonObj = jsonArr.getJSONObject(i);
        Vector<String> data = new Vector<>();

        data.add(jsonObj.getString("FOODID"));
        data.add(jsonObj.getString("PRICE"));
        data.add(jsonObj.getString("NUM"));
        data.add(jsonObj.getString("RES"));

        dataList.add(data);
    }

    Vector<String> columnNames = new Vector<>();
    columnNames.add("foodId");
    columnNames.add("price");
    columnNames.add("num");
    columnNames.add("res");

    JTable table = new JTable(dataList, columnNames);

对于更复杂的解决方案,您必须使用TableModel