mwieczorek
mwieczorek

Reputation: 2252

Getting value from JSON response

What I need to accomplish is simple - I used OKHttp to get a JSON encoded response from my server, and I need to parse a simple (one dimensional) JSON response to extract a single value.

I've written a simple code snippet, but I'm getting an error.

Here's the code for OKHttpClient in case it matters:

OkHttpClient client = new OkHttpClient();
RequestBody formVars = new FormBody.Builder().add(..vars..).build();
Request request = new Request.Builder().url(url).post(formVars).build();
Response response = null;
try {
      response = client.newCall(request).execute();
      JSONObject jj = new JSONObject((Map) response.body());
      String e = jj.getString("status");
} catch {
      ...
}

The error I'm getting (red line) is under jj.getString("status");:

Unhandled exception: org.json.JSONException

The JSON string is simply {"status":"1"}

Upvotes: 2

Views: 17997

Answers (4)

java8.being
java8.being

Reputation: 464

Unhandled exception: org.json.JSONException

Clearly states that you are not handling this checked exception, This is how you catch exceptions.

try {
....
} catch (JSONException ex) {
  ex.printStackTrace();
}

Upvotes: 0

Dhaval
Dhaval

Reputation: 2874

You have forgotten to convert that response to string. All you need to do is following:

String stringResponse = response.body().string();

JSONObject jj = new JSONObject(stringResponse);

Upvotes: 4

Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

Change your catch clause to catch the exception like this:

try {
      response = client.newCall(request).execute();
      JSONObject jj = new JSONObject((Map) response.body());
      String e = jj.getString("status");
} catch(Exception e) {
      e.printStackTrace();
}

Upvotes: 0

Abhishek
Abhishek

Reputation: 2525

throws JSONException

add the above line to your method. and convert your response to String.

JSONObject objJsonObject = new JSONObject(response.body().toString());
System.out.println(objJsonObject.getString("status"));

also your catch block is wrong. if throws is not correct here then this would be the correct declaration. of try and catch block. add finally if required.

try {

} catch (JSONException e) {
    // TODO: handle exception
}

Upvotes: 0

Related Questions