riadrifai riadrifai - 3 months ago 12
Android Question

How to convert a GoogleJsonResponseException into a JSONObject in android/java?

In my android app, I am handling GoogleJsonResponseException, and depending on its ResultCode and message I should have different code.

try {
//type method here

} catch (GoogleJsonResponseException j) {


int satusCode = j.getStatusCode();
String message = getMessageCode(j.toString());}


Where getMessage(String s) is a method that returns the exception in this String form:

{
"code": 409,
"errors": [
{
"domain": "global",
"message": "Error message",
"reason": "conflict"
}
],
"message": "Error message"}


And i need the data inside "message". So is there a way I could change this string into a JSONObject or make convert the GoogleJsonResponse exception from the beginning to a JSONObject? Or should I parse the string manually?

Thanks

Answer

JSONObject has a constructor that accepts a string. Have you tried that?

Otherwise, reading the documentation, I see

j.getDetails().getMessage()

And since it wasn't clear which message field you wanted, here's the nested one.

j.getDetails().getErrors().get(0).getMessage();