Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.alibaba.fastjson.JSONArray
时间: 2023-10-05 13:11:41 浏览: 170
This exception occurs when you try to cast a JSON object to a JSON array.
In other words, you are trying to treat a JSON object as if it were an array, which is not possible.
To resolve this issue, you need to check the type of the JSON object before casting it. If it is an object, you should access its properties using the `get()` method. If it is an array, you should access its elements using a loop or an iterator.
Here's an example of how to do this:
```
JSONObject jsonObject = JSON.parseObject(jsonString);
if (jsonObject instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) jsonObject;
for (Object obj : jsonArray) {
// Process each element in the array
}
} else if (jsonObject instanceof JSONObject) {
JSONObject jsonObj = (JSONObject) jsonObject;
// Access properties using the get() method
String name = jsonObj.getString("name");
int age = jsonObj.getIntValue("age");
// etc.
} else {
// Handle other types of JSON data (e.g. null, boolean, number, etc.)
}
```
By checking the type of the JSON object before casting it, you can avoid the ClassCastException and handle different types of JSON data appropriately.
阅读全文