Java.lang.ClassCastException when reading the json file using java

javajsonweb services

I want to read a .json file called (results.json) using java and extract the values of the array by the key 'title'.

This is my .json file

 [
    {
        "title": {
            "0": "UNIQUE SIGNED HARRY POTTER DELUXE VOLUME SALESMAN DUMMY"
        }
    },
    {
        "title": {
            "0": "Harry Potter and the Philosopher's Stone by JK Rowling - Uncorrected Proof/ARC!!"
        }
    },
    {
        "title": {
            "0": "Huge Lego Lot 532 Lbs Pounds Legos Star Wars Castle Harry Potter City Minifigs"
        }
    }
]

This is the java code i'm using

public class JJ {

public static void main(String[] args)
{        
    readJsonFile();
}

public static void readJsonFile() {

    BufferedReader br = null;
    JSONParser parser = new JSONParser();

    try {

        String sCurrentLine;

        br = new BufferedReader(new    FileReader("C:/wamp/www/epsilon/results.json"));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println("Names of the Books:\t" + sCurrentLine);

            Object obj;
            try {

                obj = parser.parse(sCurrentLine);
                JSONObject jsonObject = (JSONObject) obj;
                String name = (String) jsonObject.get("title");

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
}

I'm getting an error saying

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject.

Best Answer

It's pretty simple. Your Json file has an array at the top level. When the JSonParser parses it, it's returning it as a JSONArray. You're trying to cast it to a JSONObject instead (which is like a map, or dictionary.) What you need to do is this:

Object obj;
try {

    obj = parser.parse(sCurrentLine);
    JSONArray jsonArray = (JSONArray) obj;
    for(obj : jsonArray){//not sure of the exact syntax, I don't have an IDE in front of me.
        JSONObject jsonObject = (JSONObject)obj;
        JSONObject realTitle = (JSONObject)jsonObject.get("0");
        String name = (String) realTitle.get("title");
    }


} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}