You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中如何提取JSON对象内callingCodes数组的元素值

问题原因

你遇到的org.json.JSONException: Index 0 out of range [0..0)报错,本质是实际返回的JSON数据中,存在部分条目的callingCodes字段为空数组(长度为0),此时直接访问下标0就会触发数组越界异常。你提供的示例JSON中该字段均有值,但完整接口返回的数据中一定存在空的callingCodes条目。

修复方案

需要在读取callingCodes数组前先判断长度,同时使用更安全的getString()方法替代强制类型转换,避免类型转换异常,修改后的代码如下:

JSONArray jsonArray = new JSONArray(response);

for(int i = 0; i < jsonArray.length(); i++){
    try {
        JSONObject data = jsonArray.getJSONObject(i);
        // 先获取callingCodes数组
        JSONArray callingCodesArray = data.getJSONArray("callingCodes");
        String call = "";
        // 数组长度大于0再取值
        if (callingCodesArray.length() > 0) {
            call = callingCodesArray.getString(0);
        }
        countryOperatorList.add(new CountryOperator(
                data.getString("isoName"),
                data.getString("name"),
                data.getString("currencyCode"),
                data.getString("currencyName"),
                data.getString("currencySymbol"),
                data.getString("flag"),
                call
        ));
    } catch (JSONException e) {
        // 单个条目解析异常时跳过,避免整个列表加载失败
        e.printStackTrace();
    }
}

额外优化建议

  • 可以根据业务需求为空的callingCodes设置自定义默认值,比如"-"或者其他无区号标识
  • 单条数据解析加异常捕获的逻辑可以避免某一条数据格式异常导致整个列表解析终止

内容的提问来源于stack exchange,提问作者Horly Andelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:48:01