问题描述
你好,我简单的Json是,我遇到了org.json.JSONException错误:索引2超出范围可以帮我解决这个问题吗? :
Hello My simple Json is and i have error org.json.JSONException: Index 2 out of range can you help me to solve this problem ? :
[
{
"cat_id": 593,
"title": "آلرژی و ایمونولوژی",
"sub_cat": [
{
"cat_id": 594,
"cat_title": "متخصص",
"cat_parent_fk": 593
},
{
"cat_id": 595,
"cat_title": "فوق تخصص",
"cat_parent_fk": 593
}
]
并使用此代码获取此json,但我有一些错误,只显示了我的json> 15项目中的两项:
and get this json with this code but i have some error and just show two item of my json >15 item :
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Cats cats = new Cats();
JSONObject jsonObject = (JSONObject) response.get(i);
String cat_id = jsonObject.getString("cat_id");
String title = jsonObject.getString("title");
String image_add = jsonObject.getString("image_add");
String image = jsonObject.getString("image");
JSONArray jsonArray = jsonObject.getJSONArray("sub_cat");
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(i);
int sub_cat_id = object.getInt("cat_id");
String sub_cat_title = object.getString("cat_title");
int sub_parent_fk = object.getInt("cat_parent_fk");
Log.i("log", "onResponse: "+ sub_cat_id + sub_cat_title + sub_parent_fk);
}
cats.setCat_id(cat_id);
cats.setTitle(title);
cats.setImage(image);
cats.setImage_add(image_add);
list.add(cats);
catsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
推荐答案
而不是i
,您应该在此使用j
作为
Instead of i
you should use j
here as
JSONObject object = jsonArray.getJSONObject(j);
// ^^
让我们假设您的响应包含3个json对象,每个sub_cat
具有2个对象,因此在解析response
的第3个对象时(当i
为2时),而sublist
具有2个对象(索引为0, 1)知道(如上所述),它将尝试从2个对象的数组(sub_cat)中提取第3个对象,因此请使用
Let's assume that your response has 3 json objects and every sub_cat
has 2 objects so during the parsing of 3rd object of response
(when i
is 2) but sublist
has 2 objects (index 0,1) so know (as mentioned above) this will try to fetch 3rd object from an array(sub_cat) of 2 objects, hence the issue so use
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
// j represents the size of sub_cat. ^^
...
}
这篇关于错误org.json.JSONException:索引2超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!