Menderez Albano
Menderez Albano

Reputation: 21

Getting ClassCastException

I have an Iterator to generate objects from a JSON-format. But unfortunately I get a

ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at Main.Test.main(Test.java:33)

My Test class are as below:

public class Test {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      ArrayList al = new ArrayList(); 

      try {
         Object jsonData = parser.parse(new FileReader("C:\\Users\\b\\Desktop\\test.json"));
         JSONObject jsonObject = (JSONObject) jsonData;

         JSONIteratorAuthor itr = new JSONIteratorAuthor(jsonObject);
         while(itr.hasNext()){
            al.add(itr.next());
         }

         while(itr.hasNext()){
             Object element = itr.next();
             System.out.print(element + "");
         }        
     } 
     catch (FileNotFoundException e) {
        e.printStackTrace();
     } 
     catch (IOException e) {
        e.printStackTrace();
     } 
     catch (ParseException e) {
        e.printStackTrace();
     }
  }
}

The exception relates to this line: JSONObject jsonObject = (JSONObject) jsonData;

I really don't understand why it doesn't work. I hope someone can help me. I use the json.simple library.

Upvotes: 0

Views: 76

Answers (2)

nolexa
nolexa

Reputation: 2492

Both JSON object and JSON array are valid roots of JSON data. There's no way to query the json-simple parser what type of data comes from the call

Object jsonData = parser.parse(data);

I guess you have to use instanceof to check what type you get and then cast accordingly. Note that JSONArray does not extend JSONObject, so you can't cast between the two.

Upvotes: 1

ctst
ctst

Reputation: 1680

It seems you saved your data as type org.json.simple.JSONArray. Try casting

JSONArray jsonObject = (JSONArray) jsonData;

instead of

JSONObject jsonObject = (JSONObject) jsonData;

Upvotes: 1

Related Questions