JSON Object cannot be converted to JSON Array [duplicate]

↘锁芯ラ 提交于 2019-12-05 08:13:37

问题


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();
}


来源:https://stackoverflow.com/questions/46587719/json-object-cannot-be-converted-to-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!