Valentino Ru
Valentino Ru

Reputation: 5052

Android check if server response "is" a JSON

Like you know, a php mysql_query() request returns false if the query was not successful. With time, I formed a habit (you should tell me if it's a bad one) to make something like

$res = mysql_query(...);

if($res == false){
    echo json_encode("notOK");
}else{
    $return = array();
    // process query result into that array
    echo json_encode($return);
}

The processing of the response works well in JavaScript by doing something like

// (...)
success : function(response){
    var res = JSON.parse(resonse);
    if(res == "notOK"){
        // error handling
    }else{
        // proceed 
    }
}
// (...)

However, in Android this seems not to work. My standard process to handle the server request is

HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
Vector<JSONObject> vector = new Vector<JSONObject>();

try{
    response = client.execute(get);         
    HttpEntity entity = response.getEntity();

    if(entity != null){
        InputStream in = entity.getContent();
        String result = convertStreamtoString(in);

        JSONArray resultArray = new JSONArray(result);

        int len = resultArray.length();

        for(int i=0; i<len; i++){
            vector.add(resultArray.getJSONObject(i));
        }

        in.close();
    }
} catch (//...

This results in a JSONException which reads

04-14 17:13:23.011: W/System.err(433): org.json.JSONException: Value true of type java.lang.String cannot be converted to JSONArray
04-14 17:13:23.022: W/System.err(433):  at org.json.JSON.typeMismatch(JSON.java:107)
04-14 17:13:23.022: W/System.err(433):  at org.json.JSONArray.<init>(JSONArray.java:91)
04-14 17:13:23.022: W/System.err(433):  at org.json.JSONArray.<init>(JSONArray.java:103)
04-14 17:13:23.022: W/System.err(433):  at imhotapp.schlettibusiness.rest.RestHandler.login(RestHandler.java:52)
04-14 17:13:23.022: W/System.err(433):  at imhotapp.schlettibusiness.LoginActivity.tryLogin(LoginActivity.java:48)
04-14 17:13:23.030: W/System.err(433):  at java.lang.reflect.Method.invokeNative(Native Method)
04-14 17:13:23.030: W/System.err(433):  at java.lang.reflect.Method.invoke(Method.java:507)
04-14 17:13:23.030: W/System.err(433):  at android.view.View$1.onClick(View.java:2139)
04-14 17:13:23.030: W/System.err(433):  at android.view.View.performClick(View.java:2485)
04-14 17:13:23.030: W/System.err(433):  at android.view.View$PerformClick.run(View.java:9080)
04-14 17:13:23.030: W/System.err(433):  at android.os.Handler.handleCallback(Handler.java:587)
04-14 17:13:23.030: W/System.err(433):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-14 17:13:23.030: W/System.err(433):  at android.os.Looper.loop(Looper.java:123)
04-14 17:13:23.030: W/System.err(433):  at android.app.ActivityThread.main(ActivityThread.java:3683)
04-14 17:13:23.030: W/System.err(433):  at java.lang.reflect.Method.invokeNative(Native Method)
04-14 17:13:23.030: W/System.err(433):  at java.lang.reflect.Method.invoke(Method.java:507)
04-14 17:13:23.030: W/System.err(433):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-14 17:13:23.030: W/System.err(433):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-14 17:13:23.030: W/System.err(433):  at dalvik.system.NativeStart.main(Native Method)

Is there a way to handle that like in Javascript? Am I doing something fundamentally wrong?

PS: I found this question here, but i do not think that it is a duplicate, because here it's about checking if an object is even 'JSON-familiar' or not

Upvotes: 3

Views: 4732

Answers (2)

user1885718
user1885718

Reputation: 161

According to : http://www.ietf.org/rfc/rfc4627.txt is should be "application/json".

boolean isJSON = "application/json".equalsIgnoreCase(entity.getContentType());

Upvotes: 0

Perception
Perception

Reputation: 80603

Ok, the problem is that sometimes your returned data represents a JSON object, and other times it represents a JSON array. Your Android code is treating the data as an array in all cases. You can handle this, but not with the JSON.org library you are using now. Since you are developing for Android you have built in access to the Gson library - and with it you can do this:

JSONElement jsonElem = new JsonParser().parse(result);
if(jsonElem.isJsonArray()) {
    // Normal data
} else {
    // 'Error' data'
}

Pretty simple. Do note however that you should really indicate error conditions with an appropriate HTTP status code (one of the 50x codes), as opposed to just relying on the returned data.

Upvotes: 2

Related Questions