在 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);
// 處理數組
}
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
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;
}
| 類型 | 首字符 | 示例 |
|---|---|---|
| JSONObject | { | {"code": 200, "msg": "success"} |
| JSONArray | [ | [{"id": 1}, {"id": 2}] |
| 字串 | " | "hello" |
| 數字 | 0-9/- | 123 |
| 布爾 | t/f | true |
| null | n | null |
optInt/optString 等安全獲取方法,避免異常