0

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.

2 Answers 2

1

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

JSONArray jsonObject = (JSONArray) jsonData;

instead of

JSONObject jsonObject = (JSONObject) jsonData;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.