{
"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());
}
谁能帮我解决这个问题吗?
最佳答案
您的代码中有几处看起来不正确,但因为我没有完整的上下文,所以有两件事特别奇怪:
- 您的 for 循环从 0 到
response.length()
,这可能比product_array
中的对象还要多。因此,您可能会遇到product_array.getJSONObject(i);
超出范围的异常,您可能需要使用product_array.size()
或product_array.length()
, depending on your import . - 您的
if..else if
不正确。您检查两次status.equals("true")
,这意味着代码永远不会到达第二个if
。
关于java - JSON索引2超出范围异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393827/