2

I have the following json formatted string that is returned from the web service:

{"Success":false,"Message":"This version is not supported"}

I am using the following code to invoke the web service:

AsyncHttpClient client = new AsyncHttpClient();

client.get("http://mywebsite/check/getcompatibilityinfo", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});

The response contains the json string now I need to access the Success and the Message property. Is there any simple way to do it without using complicated third party libraries?

7
  • response.optString("Success") will work here. Doesn't get easier than this. :) Feb 4, 2014 at 21:58
  • optString is not defined!!!
    – john doe
    Feb 4, 2014 at 21:59
  • The response you get back must be a JSONObject right? On that call response.optString. If your JSON is the one above, it will work. Feb 4, 2014 at 22:02
  • The response I get back is a JSON string as indicated in the code above.
    – john doe
    Feb 4, 2014 at 22:03
  • Right, then @MiStr's answer is right. Just use optString and optBoolean instead of getString and getBoolean. Feb 4, 2014 at 22:05

1 Answer 1

11

The JSONObject class is already available in your Android codebase (no 3rd party dependencies). Since your example uses normal (simple) JSON, you can use:

try {
    JSONObject responseJSON = new JSONObject(response);
} catch (JSONException e) {
    e.printStackTrace();
}

boolean success = responseJSON.getBoolean("Success");
String message = responseJSON.getString("Message");
3
  • you might add some defensive codes and check to see that the object exists first: if (!responseJSON.isNull("Success") { boolean success = responseJSON(getBoolnea("Success")};
    – Martin
    Feb 4, 2014 at 22:04
  • ...as well as checking for the exception when calling constructor for JSONObject :)
    – Melquiades
    Feb 4, 2014 at 22:06
  • Yeah I wrapped in try/catch blocks and now it is okay. I am surprised that Java will force me to include the try/catch blocks. This is insane!
    – john doe
    Feb 4, 2014 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.