首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 解析服務器響應判斷 JSONObject 與 JSONArray 的方法

     編輯:程式設計綜合問答

在 Android 網絡請求中,服務器可能返回 JSONObject (對象) 或 JSONArray (數組),直接強制轉換會拋出 JSONException。需先檢查響應字串首字符或使用 try-catch 兼容處理。

問題代碼


// 直接嘗試轉 JSONObject,若響應是 JSONArray 會崩潰
JSONObject json = new JSONObject(jsonResponse); // JSONException: Value [...] cannot be converted to JSONObject

解決方案

方法一:檢查首字符 (最高效、推薦)


public static boolean isJsonArray(String json) {
    if (json == null || json.trim().isEmpty()) return false;
    String trimmed = json.trim();
    return trimmed.startsWith("[");
}

public static boolean isJsonObject(String json) {
    if (json == null || json.trim().isEmpty()) return false;
    String trimmed = json.trim();
    return trimmed.startsWith("{");
}

// 使用
String response = ...;
if (isJsonObject(response)) {
    JSONObject obj = new JSONObject(response);
    // 處理對象
} else if (isJsonArray(response)) {
    JSONArray arr = new JSONArray(response);
    // 處理數組
}

方法二:try-catch 兼容解析 (簡單、性能稍低)


public static Object parseJson(String json) {
    try {
        return new JSONObject(json);
    } catch (JSONException e1) {
        try {
            return new JSONArray(json);
        } catch (JSONException e2) {
            return null; // 非法 JSON
        }
    }
}

// 使用
Object parsed = parseJson(response);
if (parsed instanceof JSONObject) {
    JSONObject obj = (JSONObject) parsed;
} else if (parsed instanceof JSONArray) {
    JSONArray arr = (JSONArray) parsed;
}

方法三:Gson/Jackson 庫自動適配 (現代推薦)


// Gson
JsonElement element = JsonParser.parseString(response);
if (element.isJsonObject()) {
    JsonObject obj = element.getAsJsonObject();
} else if (element.isJsonArray()) {
    JsonArray arr = element.getAsJsonArray();
}

// 或直接映射到模型 (需確定類型)
MyResponseModel model = new Gson().fromJson(response, MyResponseModel.class);

完整錯誤碼檢查示例


public static boolean checkForError(String jsonResponse) {
    try {
        // 先判斷類型
        if (isJsonObject(jsonResponse)) {
            JSONObject json = new JSONObject(jsonResponse);
            if (json.has("code")) {
                int code = json.optInt("code", -1);
                return code == 99; // 錯誤碼 99
            }
        } else if (isJsonArray(jsonResponse)) {
            // 數組通常不包含錯誤碼,或第一個元素包含
            JSONArray arr = new JSONArray(jsonResponse);
            if (arr.length() > 0 && arr.get(0) instanceof JSONObject) {
                JSONObject first = arr.getJSONObject(0);
                if (first.has("code")) {
                    return first.optInt("code", -1) == 99;
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return false;
}

JSON 格式對比

類型首字符示例
JSONObject{{"code": 200, "msg": "success"}
JSONArray[[{"id": 1}, {"id": 2}]
字串""hello"
數字0-9/-123
布爾t/ftrue
nullnnull

最佳實踐建議

  1. 協議層面約定:成功返回對象,錯誤返回對象含 code/msg,避免混合類型
  2. 使用 optInt/optString 等安全獲取方法,避免異常
  3. 統一使用 Gson/Moshi 等庫處理,自動適配類型
  4. 網絡層統一解析封裝,業務層只處理模型對象
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved