Tyrick
Tyrick

Reputation: 2966

Retrieving an particular element from JSONArray

How can I retrieve "B2" from the following? JSONArray?

        JSONArray o = new JSONArray();
    for(int i = 0; i < 3; i++) {
        List<Object> list = new ArrayList<Object>();
        list.add("B" + i);
        list.add(100+i);
        o.put(list);
    }

I'm thinking it's something like the following, although this isn't at all correct.

o.get(2)[0]

Upvotes: 1

Views: 167

Answers (2)

Vito Gentile
Vito Gentile

Reputation: 14356

You've created an array of bidimensional arrays. The following code snippet should work:

o.getJSONArray(2).getString(0);

Upvotes: 0

Lukas Knuth
Lukas Knuth

Reputation: 25755

The problem is that you're using put(), which:

Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.

So, this will add an array into your array. Something like this:

[
  [
    "B1", "B2"
  ]
]

If this was intended, then you'll first need to get the inner array and then it's second entry:

o.getJSONArray(0).getInt(1);

Otherwise, if you want to fill your existing JSONArray o with the entries from the List, you'll want to use the JSONArray(Collection)-constructor.

Upvotes: 1

Related Questions