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

如何在Java中遍历嵌套JSON对象,提取共存的account_id与id

解决方法

你的代码核心问题是误用了同一个索引i同时遍历sections数组和每个section下的content数组,而且仅针对特定type的section处理,未遍历每个section下的所有content元素。以下是修正后的实现:

修正后的代码

public void getSections() {
    disposables.add(repository.getContent()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableObserver<Content>() {
                @Override
                public void onNext(@NonNull Content content) {
                    List<String> idList = new ArrayList<>();

                    // 遍历所有sections
                    for (Section section : content.getContent().getSections()) {
                        // 跳过content为null的情况,避免空指针
                        if (section.getContent() == null) {
                            continue;
                        }
                        // 遍历当前section下的所有content元素
                        for (ContentItem item : section.getContent()) {
                            // 检查当前item是否同时存在account_id和id
                            if (item.getAccountId() != null && item.getId() != null) {
                                idList.add(item.getAccountId() + ":" + item.getId());
                            }
                        }
                    }

                    sectionsIdsString = String.join(",", idList);
                    getMoreContent(sectionsIdsString);
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    // 建议添加错误处理,比如打印日志或提示用户
                    e.printStackTrace();
                }

                @Override
                public void onComplete() {}
            }));
}

关键改进点

  • 嵌套遍历:外层遍历所有sections,内层遍历每个section下的content数组,确保不遗漏任何元素
  • 通用判断逻辑:不再局限于特定type的section,只要元素同时包含account_id和id就提取,适配动态JSON结构
  • 空指针防护:增加section.getContent() == null的判断,避免潜在的空指针异常
  • 代码简洁性:使用增强for循环替代索引遍历,可读性更强

额外提示

如果你的Content、Section、ContentItem是通过Gson或其他JSON解析库生成的实体类,需确保字段映射正确(比如account_id对应accountId,符合Java驼峰命名规范)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:58:15