Mahdi.Pishguy Mahdi.Pishguy - 5 months ago 26
Android Question

Android get Index 1 out of range on parse json format

i'm trying to parse this below json format such as:

[
[
{
"mobileNumber":"<Censored>","contactUserId":"17",
"userEwallets":
[
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"}
]
}
]
,
[
{
"mobileNumber":"<Censored>","contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]
]


for parsing second json array of that as

[
{
"mobileNumber":"<Censored>",
"contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]


i get this error:

Index 1 out of range [0..1)


from below code my code can only parse the first array of that, for second array i get exception when i try to get
mobileNumber
of second json array object

for (int i = 0; i < response.length(); i++) {
try {
JSONArray jsonArray = response.getJSONArray(i);
final String mobileNumber = jsonArray.getJSONObject(i).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(i).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(i).getString("userEwallets");

Log.e("MobileNumber ", mobileNumber);

JSONArray ewallets = new JSONArray(userEwallets);
for (int j = 0; j < ewallets.length(); j++) {
JSONObject ewalletObject = ewallets.getJSONObject(j);
final String accountNumber = ewalletObject.getString("accountNumber");

Log.e("accountNumber ", accountNumber);

}
} catch (JSONException e) {
e.printStackTrace();
}
}

Answer

Try this one...

 JSONArray response;
        try {
            response = new JSONArray(res);
            for (int i = 0; i < response.length(); i++) {
                JSONArray insideJSONArray = response.getJSONArray(i);
                JSONObject jsonObject = insideJSONArray.getJSONObject(0);
                String mobileNumber = jsonObject.getString("mobileNumber");
                Log.e("TAG", "mobileNumber: " + mobileNumber);
                String contactUserId = jsonObject.getString("contactUserId");
                Log.e("TAG", "mobileNumber: " + contactUserId);
                JSONArray userEwallets = jsonObject.getJSONArray("userEwallets");
                for (int j = 0; j < userEwallets.length(); j++) {
                    JSONObject ewalletObject = userEwallets.getJSONObject(j);
                    final String accountNumber = ewalletObject.getString("accountNumber");
                    Log.e("accountNumber ", accountNumber);

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
Comments