JSON returning html

4

I'm returning a JSON from a server using PHP with the simple code:

<?php
$response = array();
$response["success"] = 1;
echo json_encode($response);

I'm getting the answer through an android app, however with the following error:

  

Error parsing data org.json.JSONException: Value <html> of type java.lang.String can not be converted to JSONObject

I suspect the server is sending something else along with JSON. What do you do to prevent this?

    
asked by anonymous 26.02.2014 / 22:24

1 answer

3

The error received

Generally, the error Error parsing data org.json.JSONException ... refers to the inability to process JSON.

For your particular case, you can read in the error message:

  

Error parsing data org.json.JSONException: Value of type java.lang.String can not be converted to JSONObject

What translated:

  

Error processing data org.json.JSONException: Value of type java.lang.String can not be converted to JSONObject

That tells us that a string is being sent instead of an object, as expected.

Dealing with error

One way to deal with error in scenarios like this is to wrap your code in a try...catch so you can try to work the data you receive while being able to catch any errors in a way that deal with them:

try {
    JSONObject jobj = new JSONObject(response);
    String succes = jobj.getString("success");
    ...
} catch (JSONException e) {
    // ups, correu mal... vamos ver o que aconteceu
    e.printStackTrace();
}
    
26.02.2014 / 22:57