java - JSON索引2超出范围异常

标签 java json

{
    "status": "true",
    "value": {
        "products": [
            {
                "id": "1",
                "store_categories_id": "10",
                "description": "Chicken Briyani",
                "unit_price": "120",
                "pro_descripaation": "",
                "pro_image": ""
            },
            {
                "id": "2",
                "store_categories_id": "10",
                "description": "Vegetable Thali",
                "unit_price": "100",
                "pro_descripaation": "",
                "pro_image": ""
            }
        ]
    }
}

错误:org.json.JSONException:索引 2 超出范围 [0..2)

try{
    JSONArray product_array = value_array.getJSONArray("products");
    for (int i = 0; i < response.length(); i++) {
        if (status.equals("true")) {
            // progressDialog.dismiss();

            Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
        } else if (status.equals("true")) {

            // progressDialog.dismiss();
            JSONObject jsonobject = product_array.getJSONObject(i);

            ProductList productList = new ProductList();

            productList.setDescription(jsonobject.getString(Constants.KEY_PRODUCT_DESCRIPTION));

            productList.setId(jsonobject.getString(Constants.KEY_PRODUCT_ID));
            Log.v("ganesh","keyboard");
            productListArray.add(productList);
            adapter.notifyDataSetChanged();
        }
    }
} catch (JSONException exception) {
    // progressDialog.dismiss();
    Log.e("--JSON EXCEPTION--", exception.toString());
}

谁能帮我解决这个问题吗?

最佳答案

您的代码中有几处看起来不正确,但因为我没有完整的上下文,所以有两件事特别奇怪:

  1. 您的 for 循环从 0 到 response.length(),这可能比 product_array 中的对象还要多。因此,您可能会遇到 product_array.getJSONObject(i); 超出范围的异常,您可能需要使用 product_array.size()product_array.length(), depending on your import .
  2. 您的if..else if不正确。您检查两次 status.equals("true"),这意味着代码永远不会到达第二个 if

关于java - JSON索引2超出范围异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393827/

相关文章:

java - ArrayAdapter.addAll(T... items) 未被 eclipse 标记

javascript - 对于 Prisma Client 连接查询,是否可以将深度嵌套的字段移动到结果的顶层?

c# - JsonProperty c# 将字典值序列化为数组

java - 用java中的空格替换json字符串中的特殊字符(不可打印的字符)

json - GoLang Json 福汇

java - 在 javascript 中创建 json 对象并将其发送到 servlet

java - 打开 Eclipse IDE 时收到 verify.dll not found 错误消息

java - 为什么 toMap 的错误放置会导致 RXJava 出现问题?

java - 检测列表中的多个值

javascript - 如何通过jquery生成动态图像标签