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

Android开发:如何从嵌套JSON数组中获取数据?

解决嵌套JSON数组读取失败的问题

嘿,我看了你的代码和提供的JSON数据,整体逻辑是没问题的,但大概率是几个小细节绊住了你,导致读不到嵌套的comments_data数组里的数据,咱们一步步来排查解决:

1. 先处理空值/缺失字段引发的异常

看你的JSON数据里,有些字段是空的——比如id为6的评论里rating是空字符串,还有的comment也是空值。你现在用的getString()方法在遇到空字段或者字段不存在时会直接抛出JSONException,导致循环直接中断,后面的数据就都读不到了。

建议换成optString()方法,它会在字段不存在或为空时返回空字符串,不会抛出异常:

String Namee = object1.optString("username");
String Ratingg = object1.optString("rating");
String Commentt = object1.optString("comment");

2. 确认comments_data数组是否存在

虽然你给的JSON里每个data元素都有comments_data,但实际接口返回可能存在某些元素没有这个数组的情况。直接调用getJSONArray()会抛出异常,所以最好先判断一下:

if (object.has("comments_data")) {
    JSONArray jarray1 = object.getJSONArray("comments_data");
    // 内层循环的逻辑放在这里
}

3. 检查commentsList是否初始化

如果你的commentsList只是声明了但没初始化(比如只写了List<Comments> commentsList;,没写commentsList = new ArrayList<>();),那往里面加元素的时候会抛出空指针异常,导致数据根本存不进去。一定要确保集合初始化完成。

4. 优化后的完整代码

结合上面的几点,优化后的代码如下:

JSONObject jsono = new JSONObject(res);
// 先判断接口返回状态是否成功,避免无效解析
if (jsono.getString("status").equals("success")) {
    JSONArray jarray = jsono.getJSONArray("data");
    // 确保commentsList已初始化
    if (commentsList == null) {
        commentsList = new ArrayList<>();
    }
    for (int i = 0; i < jarray.length(); i++) {
        JSONObject object = jarray.getJSONObject(i);
        // 先判断是否存在comments_data数组
        if (object.has("comments_data")) {
            JSONArray jarray1 = object.getJSONArray("comments_data");
            for (int j = 0; j < jarray1.length(); j++) {
                JSONObject object1 = jarray1.getJSONObject(j);
                // 用optString安全获取字段值
                String username = object1.optString("username");
                String rating = object1.optString("rating");
                String comment = object1.optString("comment");
                String userImage = object1.optString("userimage");

                Comments comments1 = new Comments();
                comments1.setUsername(username);
                comments1.setRating(rating);
                comments1.setComments(comment);
                // 这里可以根据userimage是否为空,设置网络头像或者默认图
                comments1.setProfileimage(R.drawable.fav);
                
                commentsList.add(comments1);
            }
        }
    }
}

5. 调试小技巧

要是还是有问题,加几个日志排查一下:

  • 打印jarray1.length(),看看是否正确获取到嵌套数组的长度,确认有没有进入内层循环:
Log.d("CommentDebug", "当前comments_data数组长度: " + jarray1.length());
  • 打印每个嵌套的JSON对象内容,确认解析是否正确:
Log.d("CommentDebug", "当前评论对象: " + object1.toString());

按照上面的步骤调整,应该就能顺利读取到嵌套数组里的数据啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:48:18