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 trial

Android Build a Weather App (2015) Working with JSON Using JSONObject

JSONChallenge

Please help me to find out where I did wrong in this piece of code from the JSON Challenge.

JSONChallenge.java
// A JSONObject variable named 'jsonData'
String json;
JSONObject jsonData =new JSONObject(json);
// was loaded from the data.json file.
String name=jsonData.getString("name");
String publisher=jsonData.getString("publisher");
String language = jsonData.getString("language");
data.json
{
    "name":"Treehouse Book Series",
    "publisher":"Wiley",
    "language":"English",
    "books":[
        {
            "title":"HTML5 Foundations",
            "author":"Matt West",
            "pages":384
        },
        {
            "title":"CSS3 Foundations",
            "author":"Ian Lunn",
            "pages":352
        }
    ]
}

1 Answer

Kunal Bhuwalka
Kunal Bhuwalka
34,149 Points

There are two small errors with the code. Don't worry, they are just minor oversights.

  1. The String needs to be initialized. For the challenge, it doesn't matter even if the initialization is an empty string. However, I suggested always have relevant Strings.
  2. The creation of the JSONObject needs to be enclosed in a try-catch block. You need to handle the exception. Here is a working code just to help you get going...
// A JSONObject variable named 'jsonData'
String json = "";
try{
   JSONObject jsonData =new JSONObject(json);
}catch(JSONException e){
   //Handle the exception here
}
// was loaded from the data.json file.
String name=jsonData.getString("name");
String publisher=jsonData.getString("publisher");
String language = jsonData.getString("language");

Thank you Kunal, from the tutorial i learned that the JSONObject must be enclosed in a try and catch block as you also mentioned, but the thing is that I tried to do this in the challenge but it did not work. Anyway I resolve the problem. The problem was that in this challenge is not required to declare the jsonData variable for JSONObject, because this supposed to be by default. I just comment out the JSONObject and the code executed successfully.