Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

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

I need to read a JsonArray data from a file (on an SD card) and store it into a SQLite database.

but I am getting a java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray exception while parsing data to JsonArray.

Data in the file is very huge, the whole data can not be stored in a single String or String Buffer or String Builder.

Here is my code.

FileReader fileReader = new FileReader(file_path);
Object obj = jsonParser.parse(fileReader);
JSONArray jsonArray = (JSONArray) obj; // Exception.

Please help..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...