Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBianca Power
1,249 PointsHelp with Getting Data From the Web final challenge
Hi,
I'm having trouble with this, would really appreciate any help!
Here is my code:
// JSONObject 'jsonData' was loaded from data.json
String name = jsonData.getString("name"); String publisher = jsonData.getString("publisher"); String language = jsonData.getString("language");
JSONArray jsonBooks = jsonData.getJSONArray("books"); for(int i = 0; i < jsonData.length(); i++){ JSONObject jsonStuff = jsonData.getJSONObject(i); String title = jsonStuff.getString("title"); String pages = jsonStuff.getString("pages"); Log.i("CodeChallenge", title + ", " + pages); }
And this is the error I am getting:
JavaTester.java:59: getJSONObject(java.lang.String) in org.json.JSONObject cannot be applied to (int) JSONObject jsonStuff = jsonData.getJSONObject(i); ^ 1 error
1 Answer
Kevin Haube
12,265 PointsYour for
loop is looping through the wrong thing.
for(int i = 0; i < jsonBooks.length(); i++) {
JSONObject jsonStuff = jsonBooks.getJSONObject(i);
String title = jsonStuff.getString("title");
String pages = jsonStuff.getString("pages");
Log.i("CodeChallenge", title + ", " + pages);
}
In your condition, you had jsonData.length()
intead of jsonBooks.length()
, and within the body of the loop, the line
JSONObject jsonStuff = jsonBooks.getJSONObject(i);
was also trying to access jsonData as a whole instead of the jsonBook found at the index given. :) You gave a .length();
and index
value to jsonData, and because it is not a JSONArray
, it had no idea what to do with it. The array is always what you want to pass an index to.
When tested, the above for
loop gives a successful answer.