I am doing some REST calls, and getting the response. Some times, the response will not be ok, so I need to parse the response, and present it in a proper way for the user to notice, and react. I have this code:
if(response.code()!=200){
JSONArray jsonError=null;
try {
Log.i("David", "Incorrect response: "+response.errorBody().string());
jsonError = new JSONArray(response.errorBody().string());//After this line, jsonError is null
JSONObject message=jsonError.getJSONObject(0);
String errorJson=message.getString("message");
Log.i("David", "Error received: "+errorJson);
AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity());
dialog.setTitle(getString(R.string.error));
dialog.setMessage(getString(R.string.errorfound) + errorJson);
dialog.setPositiveButton(getString(R.string.aceptar), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
This way, the logging line "Incorrect response" shows perfectly, with error code, message, etc. This is the JSON received:
[{"coderror":"-2","gravedad":"1","message":"Device imei 34543564768463435345 not logged in","cause":""}]
My problem is, as I said, the logging works ok, but when I try to convert the JSON to a JsonArray...it fails. JsonError object turns out to be null, in the very next line.
Why can't I parse the response? Thank you.