clems36
clems36

Reputation: 942

Android JSONArrays inside JSONArray

Here's the relevant part of my json file:

"categories": [
     [
         "Belgian Restaurant", 
         "belgian"
     ], 
     [
         "Brasserie", 
         "brasseries"
     ]
 ], 

What i want to do is retrieve informations from the second JSONArray (let's say "brasseries" for example).

The following code worked for retrieving informations from the first array:

JSONArray categories = jsonObject.getJSONArray("categories");
restaurant.setCat1(categories.getJSONArray(0).getString(1));

The result of this was "belgian" as expected, but then i tryed the same for the second array:

restaurant.setCat2(categories.getJSONArray(1).getString(1));

and that threw a Index 1 out of range [0..1) JSONException

I don't get it since indexes 0 and 1 clearly exist in the file ... Why would 0 work and not 1 ?

Upvotes: 4

Views: 194

Answers (1)

Pankaj Nimgade
Pankaj Nimgade

Reputation: 4549

the problem is that there is a array inside another array without a name, your error can be ignored like this,

restaurant.setCat2(categories.getJSONArray(0).getString(1));

before coding for any JSON data, you should always check if it is right,

as JSON in the question is lacking the KEY's for the different values that you want to iterate,

it would be difficult to get the information if the inner object change it's incessant variables, (any increase or decrease will lead to erroneous result).

try to generate JSON with key-value pair,

Example

{
  "categories": [
    {
      "id": "00",
      "name": "Some_name_0"
    },
    {
      "id": "01",
      "name": "Some_name_1"
    },
    {
      "id": "02",
      "name": "Some_name_2"
    },
    {
      "id": "03",
      "name": "Some_name_3"
    },
    {
      "id": "04",
      "name": "Some_name_4"
    }
  ]
}

Upvotes: 2

Related Questions