JSON对象无法转换为JSON数组

时间:2017-10-05 14:05:59

标签: java android json jsonexception

当我尝试从服务器转换以下JSON响应字符串时,我收到此错误。我希望处理JSONObject或JSONArray,具体取决于服务器的响应,因为它大多数时候返回JSONArray。

来自服务器的JSON响应

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

Java代码如下

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

错误日志:

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)

任何人都可以帮助我。

由于

3 个答案:

答案 0 :(得分:3)

根据你回答1的评论,你可以做到

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

答案 1 :(得分:2)

您的回复{"message":"No Results found!","status":"false"}不是数组。这是一个对象。在代码中使用JSONObject代替JSONArray

提示:数组用方括号[]包裹,对象用大括号{}包裹。

答案 2 :(得分:0)

我通过编写以下代码解决了这个问题[恭喜@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();
}