Search code examples
javajsonorg.json

How to parse JSONArray which is in another JSONArray


I am trying to parse a JSONObject. This JSONObject has a JSONArray in it, and it has another JSONArray inside of JSONArray. The json form that I am trying to parse is as below.

{
    "phone":"01029093199",
    "store_id":"1",
    "orders":[
        {
            "menu_id":"4",
            "menu_defaultprice":"1500",
            "extraorders":[
                {
                    "extra_id":"1",
                    "extra_price":"0",
                    "extra_count":"1"
                },
                {
                    "extra_id":"38",
                    "extra_price":"300",
                    "extra_count":"2"
                }
            ]
        },
        {
            "menu_id":"4",
            "menu_defaultprice":"1500",
            "extraorders":[
                {
                    "extra_id":"2",
                    "extra_price":"0",
                    "extra_count":"1"
                },
                {
                    "extra_id":"19",
                    "extra_price":"500",
                    "extra_count":"1"
                }
            ]
        },
        {
            "menu_id":"6",
            "menu_defaultprice":"2000",
            "extraorders":[
                {
                    "extra_id":"6",
                    "extra_price":"0",
                    "extra_count":"1"
                },
                {
                    "extra_id":"21",
                    "extra_price":"500",
                    "extra_count":"1"
                },
                {
                    "extra_id":"41",
                    "extra_price":"300",
                    "extra_count":"1"
                }
            ]
        }
    ]
}

The code below is what I have tried before.

@RestController
public class OrderApiController {

    private OrderService orderService;

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping("/OrderInsert.do")
    public void insertOrder(@RequestBody JSONObject jsonObject) {
        JSONParser jsonParser = new JSONParser();

        System.out.println(jsonObject);
        System.out.println(jsonObject.get("phone")); // phone 가져오기 성공
        System.out.println(jsonObject.get("store_id"));  // store_id 가져오기 성공
        System.out.println("==========JSONArray Parsing start=========");
        ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
        for(int i = 0; i < jsonArrayList.size(); i++) {
            System.out.println(jsonArrayList.get(i));  // SUCCESS

            String temp = jsonArrayList.get(i).toJSONString(); // WHERE ERROR HAPPENS
            System.out.println(temp);

            // Tried below code to remove "[", "]" from JSONArray, but not working.
            // Error message was same as the message shown from line 37.
            //String jsonString = temp.substring(1, temp.length()-1);
            //System.out.println(jsonString);
            

            // org.json.JSONObject jTemp = new org.json.JSONObject(jsonArrayList.get(i));
            // System.out.println(jTemp);  --> prints {} (empty JSONObject)
            // System.out.println("menu_id : " + jTemp.getInt("menu_id")); // Not Working
        }
    }
}

The error shown is ..

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.json.simple.JSONArray

Additionally, I am using this json module dependency.

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>

I knew that if I print something on console using System.out.println(OBJECT), the OBJECT's toString() method is called. So I tried to call toString() , and that gave me the ClassCastException exception.


Solution

  • Error is in fact at ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");

    Instead of casting JSONArray to ArrayList, you can traverse JSONArray and read its attributes. Your code can be changed something like.

        @PostMapping("/OrderInsert.do")
        public void insertOrder(@RequestBody JSONObject jsonObject) {
            System.out.println(jsonObject);
            System.out.println(jsonObject.get("phone")); // phone 가져오기 성공
            System.out.println(jsonObject.get("store_id"));  // store_id 가져오기 성공
            System.out.println("==========JSONArray Parsing start=========");
            JSONArray orders = jsonObject.getJSONArray("orders");
            for(int i = 0; i < orders.length(); i++) {
                System.out.println(orders.get(i));  // SUCCESS
    
                String temp = orders.get(i).toString();
                System.out.println(temp);
    
                // Travserse further json
                JSONObject order = orders.getJSONObject(i);
                System.out.println(order.get("menu_defaultprice"));
                System.out.println(order.get("menu_id"));
                JSONArray extraorders = order.getJSONArray("extraorders");
                for(int j = 0; j < extraorders.length(); j++) {
                    JSONObject extraOrder = extraorders.getJSONObject(j);
                    System.out.println(extraOrder.get("extra_id"));
                    System.out.println(extraOrder.get("extra_price"));
                    System.out.println(extraOrder.get("extra_count"));
                }
            }
        }