How to get key value of objects inside an array in Java

Viewed 1441

I am trying to get key and value of json array response. I want to map each key and get its value. Currently I am looping the result of my response.

public void getResult(Object result) {
    ObjectMapper mapper = new ObjectMapper();
    Object map = null;
    try {
       map = mapper.readValue((String) result, Object.class);
    } catch (JsonProcessingException e) {
       e.printStackTrace();
    }

    JSONArray jsonArray = (JSONArray) map;

    for (Object o : jsonArray) {
        JSONObject json = new JSONObject((Map) o);

        for (Object obj : json.entrySet()) {
            Map.Entry entry = (Map.Entry) obj;

            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
    }
}

Here is the list of objects inside an array

[
    {
        "uniqueName": "INVinv0001-5179",
        "documentType": "Invoice",
        "description": "INVinv0001-5179",
        "assignedDate": "2020-10-22",
        "approver": "10011618",
        "email": "adrian.cabral@example.com",
        "fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
        "attachments": [
            "AEz0ACMDZtZ!cnN"
        ]
    },
    {
        "uniqueName": "INVinv0001-5179",
        "documentType": "Invoice",
        "description": "INVinv0001-5179",
        "assignedDate": "2020-10-22",
        "approver": "10003025",
        "email": "dummy@example.com",
        "fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
        "attachments": [
            "AEz0ACMDZtZ!cnN"
        ]
    }
]

I keep getting this error.

java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class org.json.simple.JSONObject 
2 Answers

Try to convert map object to JSONArray rather than JSON Object. It would give you JSONObject to work with directly.

public void getResult(Object result) {
        ObjectMapper mapper = new ObjectMapper();
        Object map = null;
        try {
            map = mapper.readValue((String) result, Object.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        JSONArray json = (JSONArray) map;
        for (int i=0; i < json.length(); i++) {
            JSONObject e = json.get(i);

            System.out.println(e);
        }
}

You are casting it wrong.

JSONObject json = (JSONObject) map;

This casting is wrong (JSONObject) map. it should be (JSONArray) map.

Next time before casing object, you perhaps want to check type of object like this.

System.out.println(map.getClass().getName());
Related