-1

I'm new to Java. Geting simple answer from server

{"response":"ok"}

I can successfully output answer from above in virtual device in Android Studio 3 with:

try {
...
String finalJson = buffer.toString();
return finalJson;
}catch...

Now I want to display only ok from server response. As I understood from How to parse JSON in Android, I need to write in try this:

JSONObject jObject = new JSONObject(finalJson);
String aJsonString = jObject.getString("response");
return aJsonString;

But getting

error: unreported exception JSONException; must be caught or declared to be thrown

I even tried this Getting String Value from Json Object Android to be sure that this is not array.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Vit
  • 396
  • 2
  • 7
  • 16

1 Answers1

1

Your error

error: unreported exception JSONException; must be caught or declared to be thrown

means that you have a non catched JSON Exception. You should catch JSONException in your catch block

try {
    return buffer.toString();
} catch (JSONException exception) {
    Log.d("JSONException", "Json exception catched :".concat(exception.getMessage()));
} finally {
    return "Json error";
}

or either throws your exception to your method :

public String methodName(Buffer buffer) throws JSONException(){
    return buffer.toString();
}
Thomas Mary
  • 1,535
  • 1
  • 13
  • 24
  • Thanks! I was using only catch (MalformedURLException e) and catch (IOException e) – Vit Feb 11 '18 at 11:28