Add a try-catch
block to handle the exception. Only when you try to parse the data, it will be validated if its valid JSON
response or error.
First try to parse Array Class
instance and if JSON
exception , then parse with ServerErrorMessage class
Add like this, and handle the exception when Syntax Exception
try{
ServerErrorMessage serverErrorMessage = gson.fromJson(
result, ServerErrorMessage.class);
}catch (JsonSyntaxException e){
// handle the exception
}
catch (JsonIOException e){
// handle the exception
}
catch (JsonParseException e){
// handle the exception
}catch (IOException e){
// handle the exception
}
Another way is to use org.json.JSONObject
like this
private boolean isValidJsonResponse(String responseString){
try {
new JSONObject(responseString);
return true;
} catch(JSONException e) {
return false;
}
}