java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray

跟風遠走 提交于 2019-11-29 07:34:23

Check your import statements at the top of your source file.

You probably have a line saying:

import org.json.JSONArray;

It should instead be:

import org.json.simple.JSONArray;

If you are working in eclipse, or any other intelligent IDE, the problem probably happened when you started typing the line starting with JSONArray. At that point, the IDE would show you different possibilities of importing the class JSONArray. You have one in org.json.JSONArray and one in org.json.simple.JSONArray. The latter is the right one, but you choose the first one and your IDE automatically added an import line at the top of your source java file.

From the exception the problem is quite apparent, the exception tells you that your obj object cannot be cast to a org.json.JSONArray object as it is really a org.json.simple.JSONArray object. (Note that there is a different between the two).

Update

If you want to use org.json.JSONArray instead, you should use another class than jsonParser as this one is from the org.json.simple package. Currently you are mixing the two libraries, and that is what causes your troubles.

You can first read the whole content of file into a String.

FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
    fileInputStream=new FileInputStream(filename);
    int i;
    while((i=fileInputStream.read())!=-1)
    {
        stringBuffer.append((char)i);
    }
    data = stringBuffer.toString();
    csvFile.delete();
}
catch(Exception e){
        LoggerUtil.printStackTrace(e);
}
finally{
    if(fileInputStream!=null){  
        fileInputStream.close();
    }
}

Now You will have the whole content into String ( data variable ).

JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);

After that you can use jsonArray as you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!