javaandroidjsonjsonexception

JSON Object cannot be converted to JSON Array


I am getting this error when I am trying to convert following JSON response string from the server. I want to process JSONObject or JSONArray depending on the response from the server as most of the time it returns JSONArray.

JSON response from server

jsonString = {"message":"No Results found!","status":"false"}

Java code is as below

try
{
    JSONArray jsonArrayResponse = new JSONArray(jsonString);
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
    {
        if(jsonArrayResponse != null && jsonArrayResponse.length() > 0)
        {
            getCancelPurchase(jsonArrayResponse.toString());
        }
    }
}
catch(JSONException e)
{
    e.printStackTrace();
}

Error Log:

org.json.JSONException: Value {"message":"No Results found!","status":"false"} of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)
at org.json.JSONArray.<init>(JSONArray.java:108)

Can anybody help me.

Thanks


Solution

  • Based on your comment to answer 1, you can do is

    String data = "{ ... }";
    Object json = new JSONTokener(data).nextValue();
    if (json instanceof JSONObject)
      //you have an object
    else if (json instanceof JSONArray)
      //you have an array