views:

57

answers:

1
{"genres":[{"total_genres":"2"},{"genre":[{"code":"CTY","name":"Country"}]},{"genre":[{"code":"HOP","name":"Hip Hop / R&B"}]}]}

I am tryin to parse the inner array "genre" out of this string. I can get an outer array "genres" if I do:

JSONObject outer=new JSONObject(returnContent);

JSONArray ja = outer.getJSONArray("genres");

How do I extract inner objects?

+2  A: 

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"}]}
David Hedlund
So these inner JSON array elements are like in a format:[{"code":"CTY","name":"Country"}]So how do I further use these elements.I m new to json conventions. S how do we use the values
Bohemian
alright, if you have a look at my edit, i've explained some bits about how you can change both your JSON string, and your implementation.
David Hedlund
Thanks buddy.That was very helpful.
Bohemian