Simple code for converting JSONObject to a List or JSONArray?

Mark picture Mark · Oct 29, 2012 · Viewed 24.4k times · Source

I've read through various threads and found similar problems, but have been pretty unsuccessful at finding a solution for my particular problem.

JSONObject orr = (JSONObject)orderRows.get("orderRows");
System.out.println("data in orr = " + orr + "orr's type = " + orr.getClass());

Returns:

data in orr = {"470":[{"locationId":2,"quantity":1,"productId":1007}],"471":[{"locationId":2,"quantity":1,"productId":1008}]}orr's type = class org.json.simple.JSONObject

I'm trying to get this data into an array/list/anything where I can use the keys, 470,471 to retrieve the data.

Any suggestions or pointers much appreciated many thanks...

To clarify:

JSONObject orr = (JSONObject)orderRows.get("orderRows");
        JSONArray orderOne = (JSONArray)orr.get("471");
        System.out.println(orderOne);
        System.out.println(orderOne.get(0));
        JSONObject orderOneKey = (JSONObject)orderOne.get(0);
        System.out.println(orderOneKey.get("productId"));

This is what I'm after, but obviously I can't do orr.get("471") as I don't know what this number will be.

EDIT: Apparently I can't answer my own question for 8 hours:

Thanks to help from a friend and some fiddling, I found a solution, I'm sure it's not the most eloquent, but it's exactly what I was after:

for(Object key: orr.keySet()) {

                JSONArray orderOne = (JSONArray)orr.get(key);
                JSONObject ordervalue = (JSONObject)orderOne.get(0);
                System.out.println(ordervalue.get("productId"));
        }

Thanks for the help and suggestions guys.

Answer

Mark picture Mark · Oct 30, 2012

Thanks to help from a friend and some fiddling, I found a solution, I'm sure it's not the most eloquent, but it's exactly what I was after:

for(Object key: orr.keySet()) {

                JSONArray orderOne = (JSONArray)orr.get(key);
                JSONObject ordervalue = (JSONObject)orderOne.get(0);
                System.out.println(ordervalue.get("productId"));
        }

Thanks for the help and suggestions guys.