4

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 ?

clems36
  • 922
  • 1
  • 13
  • 26
  • I am pretty sure there is nothing wrong in code which you have posted. May be something else is causing the issue. – Vipul Feb 01 '16 at 15:39
  • I don't know what then, it's the first time i deal with such nested JSONArrays – clems36 Feb 01 '16 at 15:41
  • I assume there is some context around `"categories"`. Are you sure that you are in the correct `JSONObject` (e.g. have you logged `categories`)? – toKrause Feb 01 '16 at 15:43
  • I just did and it correctly logs ["Brasserie","brasseries"] – clems36 Feb 01 '16 at 15:50
  • @clementino36, try this restaurant.setCat2(categories.getJSONArray(0).getString(1)); – Pankaj Nimgade Feb 01 '16 at 15:56
  • Well no because Cat2 is supposed to be taken from the second array... This will work for sure but it's not the data i wish to retrieve – clems36 Feb 01 '16 at 15:59
  • @clementino36, I can see only one element inside categories array , the first array has a nested array, so that is what you will have to do – Pankaj Nimgade Feb 01 '16 at 16:07

1 Answers1

2

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"
    }
  ]
}
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30