JSON Object cannot be converted to JSON Array [duplicate]

强颜欢笑 提交于 2019-12-03 21:59:32

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

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{}.

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