1

I have a JSONArray that needs to be inserted into a JTable, but from what I've googled I reached the conclusion that it's easier to insert a JSONArray into a JTable by converting it into a JSONObject and then I can insert it to the JTable using an ArrayList.

I've managed to convert the JSONArray to a JSONObject as shown below, but I'm stuck when I try to convert it into an Arraylist and then inserting it into the JTable. Can you tell me how to do it? Is there an easier way to insert the JSONArray into a JTable?

JSONArray:

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

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":""}

JSONArray to JSONObject conversion program:

JSONArray jsonArr = new JSONArray(lineRead);
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < jsonArr.length(); i++) {

    JSONObject jsonObj = jsonArr.getJSONObject(i);
    Data data = new Data();

    data.foodid = jsonObj.getString("FOODID");
    data.price = jsonObj.getString("PRICE");
    data.num = jsonObj.getString("NUM");
    data.res = jsonObj.getString("RES");

    dataList.add(data);
}

1 Answer 1

2

JTable can use a Vector<Vector<String>> as a simple table model. So if you just need to display the values the following rather simplistic approach works:

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

For a more sophisticated solution you have to use a TableModel.

Sign up to request clarification or add additional context in comments.

2 Comments

why suddenly there's tableData? is the use of columnNames only for rename the column? @alexander.egger
@azizahn sorry thats a typo. changed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.