JSON Object cannot be converted to JSON Array [dup

2020-06-30 06:11发布

问题:

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

回答1:

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


回答2:

Your response {"message":"No Results found!","status":"false"} is not an array. It is an object. Use JSONObject instead of JSONArray in your code.

TIP: Arrays are wrapped in square brackets[ ] and objects are wrapped in curly braces{}.



回答3:

I fix this issue by writing following code [ courtesy @Optional ]

String jsonString = "{\"message\":\"No Results found!\",\"status\":\"false\"}";
/* String jsonString = "[{\"prodictId\":\"P00001\",\"productName\":\"iPhone 6\"},"
        + "{\"prodictId\":\"P00002\",\"productName\":\"iPhone 6 Plus\"},"
        + "{\"prodictId\":\"P00003\",\"productName\":\"iPhone 7\"}]";
 */
JSONArray jsonArrayResponse;
JSONObject jsonObject;
try {
    Object json = new JSONTokener(jsonString).nextValue();
    if (json instanceof JSONObject) {
        jsonObject = new JSONObject(jsonString);
        if (jsonObject != null) {
            System.out.println(jsonObject.toString());
        }
    } else if (json instanceof JSONArray) {
        jsonArrayResponse = new JSONArray(jsonString);
        if (jsonArrayResponse != null && jsonArrayResponse.length() > 0) {
            System.out.println(jsonArrayResponse.toString());
        }
    }
} catch (JSONException e) {
    e.printStackTrace();
}