You'd have to iterate through the array. Assuming JSONArray
for blackberry works like the java equivalent (or is it java?):
for(int i = 0; i < ja.size(); i++) {
JSONObject inner = ja.get(i);
}
As for your JSON in itself, I'd say that one would expect "genres" to be an array of genres. Now it's an array of genres + an object containing the genre count. This will totally work, and I guess at some point, the beauty of JSON is that you can do what you want with it, but it's quite unpredictable, and you'd have to modify your code to accommodate it. In my example above, for instance, you shouldn't start with i = 0
, but rather i = 1
to skip directly to the actual genres. But i'd rather change the JSON, like so:
{"total_genres":"2", "genres":[{"genre":[{"code":"CTY","name":"Country"}]},{"genre":[{"code":"HOP","name":"Hip Hop / R&B"}]}]}
Now, to look at your individual genres. "Genres" is an array of objects. Each object has only one property, "genre", which in itself contains an array. Each array contains only one item, which is an object containing code and name. This seems to me like a lot of redundant wrapping. To extract the code and the name, you'd have to do something like this:
for(int i = 1; i < ja.size(); i++) {
JSONObject inner = ja.get(i);
JSONArray innerArray = inner.getJSONArray("genre");
JSONObject evenFurtherInner = innerArray.get(0);
String code = evenFurtherInner.getString("code");
}
But I'd rather not take that approach at all. It'd be much cleaner if you could change your JSON like so:
{"total_genres":"2", "genres":[{"code":"CTY","name":"Country"},{"code":"HOP","name":"Hip Hop / R&B"}]}
Then you could do
for(int i = 0; i < ja.size(); i++) {
JSONObject genre = ja.get(i);
String code = genre.getString("code");
}
Note the use of ja.size()
. Since all your genres are in an array, you could just check the size of the array, rather than having to add an additional counter in the code being returned. So you could actually reduce your JSON even further, for best readability:
{"genres":[{"code":"CTY","name":"Country"},{"code":"HOP","name":"Hip Hop / R&B"}]}