Java项目报错:无法将元素类型Object转换为JSONObject求助
报错原因及解决方法
报错原因
JSONArray(无论使用的是org.json还是其他JSON库的实现)中的元素默认被识别为Object类型,编译器无法确认你遍历的每个元素都是JSONObject,因此直接使用for (JSONObject transaction : transactions)这种增强for循环会触发类型不匹配错误。
解决方法
方法1:遍历中强制类型转换
在循环内将每个元素强制转为JSONObject:
for (Object obj : transactions) { JSONObject transaction = (JSONObject) obj; if (transaction.getString("direction").equals("OUT")) { int amount = transaction.getInt("amount"); int rounded = (amount + 99) / 100 * 100; int roundUpAmount = rounded - amount; roundUpAmounts.add(roundUpAmount); } } return roundUpAmounts;
方法2:使用JSONArray的getJSONObject方法遍历
通过索引遍历JSONArray,直接调用getJSONObject获取指定位置的JSONObject:
for (int i = 0; i < transactions.length(); i++) { JSONObject transaction = transactions.getJSONObject(i); if (transaction.getString("direction").equals("OUT")) { int amount = transaction.getInt("amount"); int rounded = (amount + 99) / 100 * 100; int roundUpAmount = rounded - amount; roundUpAmounts.add(roundUpAmount); } } return roundUpAmounts;
额外提示
如果JSONArray中可能存在非JSONObject类型的元素,建议在转换前增加类型判断,避免运行时抛出ClassCastException:
for (Object obj : transactions) { if (obj instanceof JSONObject) { JSONObject transaction = (JSONObject) obj; // 后续业务逻辑 } }
内容的提问来源于stack exchange,提问作者NicolaHearn
相关产品推荐
相关产品推荐

