You need to enable JavaScript to run this app. 如何用for循环提取ArrayList非空元素值?以themoviedb接口logo_path获取为例
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环提取ArrayList非空元素值?以themoviedb接口logo_path获取为例

解决方案

现有代码问题说明

你当前的代码存在几个明显错误:

  • 循环内直接从外层jObject读取logo_path,而非读取production_companies数组内的单个元素属性,根本拿不到对应公司的logo值
  • production_companies.getJSONObject(i - i)永远等价于取下标为0的元素,逻辑无效
  • production_companies.getJSONObject(i+1)在循环到最后一个元素时会触发数组下标越界异常
  • 空catch块会吃掉所有异常,出问题很难排查

实现逻辑(严格匹配你的需求)

  1. 先判断production_companies数组是否为空,为空直接返回默认值
  2. 优先读取数组最后一个元素的logo_path,不为空直接使用
  3. 若最后一个元素的logo_path为null,遍历整个数组取第一个非空的logo_path
  4. 遍历完全部元素都找不到非空值的话,返回空字符串作为默认值

正确代码示例

try {
    JSONArray productionCompanies = jObject.getJSONArray("production_companies");
    int len = productionCompanies.length();
    String finalLogoPath = "";
    // 数组为空直接赋值默认值
    if (len == 0) {
        movie.setStudioUrl("");
        return;
    }
    // 第一步优先取最后一个元素的logo_path
    JSONObject lastCompany = productionCompanies.getJSONObject(len - 1);
    String lastLogo = lastCompany.optString("logo_path", "");
    if (!lastLogo.isEmpty() && !lastLogo.equalsIgnoreCase("null")) {
        finalLogoPath = lastLogo;
    } else {
        // 最后一个为空,遍历找第一个非空的
        for (int i = 0; i < len; i++) {
            JSONObject company = productionCompanies.getJSONObject(i);
            String logo = company.optString("logo_path", "");
            if (!logo.isEmpty() && !logo.equalsIgnoreCase("null")) {
                finalLogoPath = logo;
                break;
            }
        }
    }
    // 拼接url设置值
    if (!finalLogoPath.isEmpty()) {
        movie.setStudioUrl(baseUrl + MizLib.getStudioUrlSize(mContext) + finalLogoPath);
    } else {
        // 所有logo都为空的情况,可自行修改默认值
        movie.setStudioUrl("");
    }
} catch (JSONException e) {
    // 建议这里至少加个日志打印,方便后续排查问题
    e.printStackTrace();
    movie.setStudioUrl("");
}

补充说明

这里用optString而非getString,是因为optString在字段为null或者不存在的时候会直接返回默认值,不会抛出异常,更适配你接口返回logo_path可能为null的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 06:54:01