Search code examples
javaarraysjsonorg.json

JsonOjbect to Arraylist in java with org.json


The rest service that I consume returns a json object that when I print it out like this:

{"result":
[[[12,"01",1,"Fallo de corriente",0,1,"Bombeo Regatillo(Sax)"],
[12,"01",2,"Nivel máximo",0,0,"Bombeo Regatillo(Sax)"],[12,"01",3,"Nivel mínimo",0,0,"Bombeo "], 
[12,"01",6,"Exceso de caudal",0,0,"Bombeo Regatillo(Sax)"],
[12,"01",7,"Defecto de caudal",0,0,"Bombeo Regatillo(Sax)"],
[12,"02",3,"Defecto de batería",0,0,"Embalse Cabeza Pelada(Sax)"]]]}

My problem is that I want to convert it into a list and be able to access them one by one in such a way that the Arraylist is made up of each row and I can work with them one by one.

How can I pass this JsonObect to an Arraylist?

    Response response = invocationBuilder.get();
    String output = response.readEntity(String.class);

    System.out.println(response.toString());
    JSONObject bomb = new JSONObject(output);

    return bomb;

To be more precise, how to convert my JsonObject "bomb" to be able to treat it as a common arraylist and act on each row.


Solution

  • Once you have your JSON as a string, you can use the org.json library to create a map:

    // assume jsonString contains a string representation of your JSON:
    JSONObject jsonObject = new JSONObject(jsonString);
    Map<String, Object> map = jsonObject.toMap();
    

    This creates a Java map with a key value of "result", and a nested array list representing each record (i.e. JSON array).

    You can then iterate over the result. Because the data is structured as an array of arrays, you need to drill down to get the data.

    Here is one way:

    // get the value from the map we created:
    ArrayList<Object> myList = (ArrayList) map.get("result");
    
    // just so my console can handle accents:
    PrintStream out = new PrintStream(System.out, true, UTF_8);
    
    for (Object item : myList) {
        for (Object rec : (ArrayList) item) {
            ArrayList<Object> record = (ArrayList) rec;
            int item3 = (int) record.get(2);
            String item4 = (String) record.get(3);
            out.println(item3 + " - " + item4);
        }
    }
    

    This prints out the following:

    1 - Fallo de corriente
    2 - Nivel máximo
    3 - Nivel mínimo
    6 - Exceso de caudal
    7 - Defecto de caudal
    3 - Defecto de batería