Class cast exception [JSONArray cannot be cast to org.json.simple.JSONObject]

If you have a JSONObject and you are trying to convert it to a list, it is not enough to simply cast it to ArrayList as shown here.

ArrayList arrayList = (ArrayList) jsonObject.get(category);

This will throw a ClassCastException.

java.lang.ClassCastException: class org.json.JSONArray cannot be cast to class java.util.ArrayList (org.json.JSONArray is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @23ab930d; java.util.ArrayList is in module java.base of loader 'bootstrap')

This is because your JSON contains an array. So create a JSONArray and iterate over it.

JSONArray jsonArray = jsonObject.getJSONArray(category);

ArrayList<Object> arrayList = new ArrayList<Object>();
if (jsonArray != null) {
    for (int i=0; i<jsonArray.length(); i++){
        arrayList.add(jsonArray.get(i));
        System.out.println("Adding to the list {}", jsonArray.get(i));
    }
}
Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in