-1

I'm getting a JSON from the server:

                JSONObject vkjson = response.json;

I have tried to make it a string and check via LogCat to make sure it works - and yeah, it 100% works. But it is nested:

{"response":{"first_name":"...","last_name":"..."} }

I have tried to do this:

       String result = vkjson.getJSONObject("response").getString("first_name");

But IDE doesn't like the getJSONObject part and underlines it. IDE says:

Unhandled exception in org.json.JSONException

What's wrong? Is it because the JSON is loading from the server or the code is incorrect?

Thank you in advance.

asmodeoux
  • 389
  • 5
  • 14

4 Answers4

0

There's nothing wrong with your code other than not handling the JSONException which is potentially thrown (i.e. what would happen if there isn't an object called "response").

You need to look at exception handling and wrap this code in a try .. catch block or otherwise deal with the exception.

Java exception handling

Ross Taylor-Turner
  • 3,687
  • 2
  • 24
  • 33
0

Unhandled exception in org.json.JSONException

Mean that the method can throw a JSONException and you have to handle it.

So you have to:

try {
     String result = vkjson.getJSONObject("response").getString("first_name");
} catch (JSONException exception){
            //Handle exception here
}
appersiano
  • 2,670
  • 22
  • 42
0

Do this-:

try
{
 JSONObject vkjson = response.json;

  //More code related to json
}

catch(JsonException e)
{
   e.printStackTrace();
}
Shivam Oberoi
  • 1,447
  • 1
  • 9
  • 18
0
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(responseString);
                if(jsonObject != null)
                {
                    if (jsonObject.has("response")) {
                        JSONObject responseObject = jsonObject.getJSONObject("response");
                        String firstName = responseObject.getString("first_name");
                        Log.d("Tag",firstName);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
jessica
  • 1,700
  • 1
  • 11
  • 17